i have a string-array in my res/values/strings.xml
<string-array name="my_list">
<item>Item1</item>
<item>Item2</item>
</string-array>
i am accessing it in my application as and comparing it with my value in loop.
String[] myStrings = getResources().getStringArray(R.array.my_list);
for(int i=0;i<myStrings.length;i++)
{
System.out.println(myStrings[i]);
}
Now i need the search the items according to key to get the respective item.Example
<string-array name="my_list">
<item name="one">Item1</item>
<item name="two">Item2</item>
</string-array>
if my search hay key "one" then get its corresponding value(Item1).
How to accomplish this task.
Thanks
Well, I've done it using two arrays. Easy to manage as well.
One for Keys:
<string-array name="codes">
<item>AC</item>
<item>AD</item>
<item>AE</item>
</string-array>
One for Values:
<string-array name="names">
<item>Ascension</item>
<item>Andorra</item>
<item>United Arab Emirates</item>
</string-array>
And the search method.
private String getCountryByCode(String code) {
int i = -1;
for (String cc: getResources().getStringArray(R.array.codes)) {
i++;
if (cc.equals(code))
break;
}
return getResources().getStringArray(R.array.names)[i];
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="area_key">
<item>北</item>
<item>中</item>
<item>南</item>
</string-array>
<integer-array name="area_value">
<item>0</item>
<item>1</item>
<item>2</item>
</integer-array>
</resources>
Java file:
String[] areaKey = getResources().getStringArray(R.array.area_key);
int[] areaValue = getResources().getIntArray(R.array.area_value);
HashMap<String, Integer> areas = new HashMap<String, Integer>();
for (int i = 0; i < areaKey.length; i++) {
areas.put(areaKey[i], areaValue[i]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With