Nadir M. Aliyev Nadir M. Aliyev - 1 month ago 6
Android Question

Best way of getting key & value from Spinner

There are many methods for getting

Key
&
Value
from
Array
.

But what is best way getting
Key
&
Value
from an
Array
in
arrays.xml
like
key => value
via spinner?

arrays.xml:

<resources>
<string-array name="settings_listofitems">
<item name="1">item1</item>
<item name="2">item2</item>
</string-array>
</resources>


When i use code in below i get only
item value
. But i need item
key value
too:

Spinner spinner1 = (Spinner)findViewById(R.id.spinner1);
String itemvalue = getResources().getStringArray(R.array.settings_listofitems)[spinner1.getSelectedItemPosition()];


Any help is highly appreciated.

Answer

You can have Keys and Values both in separate Arrays, like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="settings_listofitems_keys">
    <item>1</item>
    <item>2</item>
</string-array>

<string-array name="settings_listofitems_values">
    <item>item1</item>
    <item>item1</item>
</string-array>
</resources>

And then parse them like this :

Spinner spinner1 = (Spinner)findViewById(R.id.spinner1);
String itemvalue = getResources().getStringArray(R.array.settings_listofitems_values)[spinner1.getSelectedItemPosition()];
String keyvalue = getResources().getStringArray(R.array.settings_listofitems_keys)[spinner1.getSelectedItemPosition()];

I hope this helps.