Reputation: 5792
I have this in my values xml file:
<string-array name="ben_country_list">
<item id="103">India</item>
<item id="210">Sri Lanka</item>
<item id="235">United Kingdom</item>
<item id="76">France</item>
<item id="216">Switzerland</item>
<item id="200">Singapore</item>
<item id="234">United Arab Emirates</item>
</string-array>
I want to get country's ID. I tried with below code:
final Spinner mBenCountry = (Spinner) findViewById(R.id.country_spinner);
mBenCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
final long ben_country = mBenCountry.getSelectedItemPosition();
final long ben_country2 = parentView.getSelectedItemId();
System.out.println(ben_country); // This one gives me position like 0,1,2...
System.out.println(ben_country2); // Output: same as above...
}
});
I want to get actual IDs of the selected item. For example, if user selects united kingdom then it should print 235
. I don't want name of that item.
Thanks for any help.
Upvotes: 0
Views: 176
Reputation: 38121
Make a separate integer-array in XML for the ids:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer-array name="ben_country_ids">
<item>103</item>
<item>210</item>
<item>235</item>
<item>76</item>
<item>216</item>
<item>200</item>
<item>234</item>
</integer-array>
</resources>
Get the int array in code:
final int[] benCountryIds = getResources().getIntArray(R.array.ben_country_ids);
Using the position
get the correct id from the array in onItemSelected
:
int countryId = benCountryIds[position];
Upvotes: 1
Reputation: 3161
First of all, android string-array XML structure doesn't support key/value pairs for item entries. So, you have to use other data source etc.: database table, CSV file or whatever else. Then load data into some collection and then pass it to custom adapter.
Upvotes: 0
Reputation: 4816
Once you have the selected item position, you can do this:
mBenCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
switch (id) {
case 103 :
System.out.println("India");
break;
case 210:
System.out.println("Sri Lanka");
break;
.
.
.
}
Upvotes: 0