Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search value for key in string-array android

Tags:

android

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

like image 870
Rishi Avatar asked Aug 31 '11 11:08

Rishi


2 Answers

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];
    }
like image 130
AlexV Avatar answered Nov 16 '22 02:11

AlexV


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]);
}
like image 37
Mike Yang Avatar answered Nov 16 '22 01:11

Mike Yang