Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I have string array that looks like this:

<string-array name="USA">
    <item name="NY">001</item>
    <item name="LA">002</item>
    <item name="WA">003</item>
</string-array>

I can get those numbers by:

Resources res = getResources();
int arryid = res.getIdentifier("USA", "array", getPackageName());
String[] numbers = res.getStringArray(arryid);

But how can I also get the names (NY,LA,WA)? Note that I have a lot of counties... Maybe use different approach?

share|improve this question
    
You can make HashMap instead. Check this – Kunu 21 hours ago
    

In official document there is no name attribute for <item>. So i don't think there will be any way to get those keys.

However if you want to get name of string or string-array, you can get it programmatically but not for the <item>.

share|improve this answer

As "001" is just the index, why not simply use that?

<string-array name="USA">
    <item>NY</item>
    <item>LA</item>
</string-array>

Then just use index + 1 for the position:

String[] usaStates = getResources().getStringArray(R.array.USA);

int index = 0;

String firstStateName = usaStates[index];
int firstStatePosition = (index + 1);

That aside, you can use two arrays and merge them into a HashMap:

<string-array name="USA">
    <item>NY</item>
    <item>LA</item>
</string-array>

<string-array name="USA_pos">
    <item>001</item>
    <item>002</item>
</string-array>

String[] usaStates = getResources().getStringArray(R.array.USA);
String[] usaStatePositions = getResources().getStringArray(R.array.USA_pos);

Map <String, String> map = new HashMap<>(usaStates.length);

for (int i = 0; i < usaStates.length; i++) {
    map.put(usaStates[i], usaStatePositions[i]);
}
share|improve this answer

Another approach would be to use a Map instead.

Have a look!

share|improve this answer
String[] numbers = getResources().getStringArray(R.array.USA);

to get data from array use.

numbers[id]

add array like this.

<string-array name="USA">
    <item>NY</item>
    <item>LA</item>
    <item>WA</item>
</string-array>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.