3

I've a Spinner, with following values/properties.

<Spinner
    android:id="@+id/spin"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:entries="@array/spin_ent"
    android:prompt="@string/spin_prompt" />

<string-array name="spin_ent">
    <item id="2">Two</item>
    <item id="1">One</item>
    <item id="3">Three</item>
    <item id="4">Four</item>
    <item id="5">Five</item>
</string-array>

From code level, I'm using the below code to get the ID of selected item.

final long spinID= ((Spinner)findViewById(R.id.spin)).getSelectedItemId();

If I select Two, I'm getting 0 instead of 2.

Why?

Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126
  • 2
    you should have implemented [OnItemSelectedListener](http://developer.android.com/guide/topics/ui/controls/spinner.html) interface and then get the selected item in [onItemSelected](http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html#onItemSelected) callback method – Anirudha Dec 29 '13 at 05:50
  • An option is to store it in an arrayList , so that you can get the item within that based on index – Viswanath Lekshmanan Dec 29 '13 at 05:51
  • 1
    [Check it](http://stackoverflow.com/a/12675836/1398150). – Harish Dec 31 '13 at 05:25

2 Answers2

2

Implement an setOnItemSelectedListener. Check the code below to help you understand better.

int count;
spinner1 = (Spinner) findViewById(R.id.spin);

spinner1 .setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                spinner1 = parent.getItemAtPosition(position).toString();
                count = position; //this would give you the id of the selected item
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });
VikramV
  • 1,111
  • 2
  • 13
  • 31
0

Ru sure item tag supports id attribute. I m finding problems here. Its returning its row_id in the spinner.

<string-array name="spin_ent">
 <item id="2">Two</item>
 <item id="1">One</item>
 <item id="3">Three</item>
 <item id="4">Four</item>
 <item id="5">Five</item>
</string-array>
Sush
  • 3,864
  • 2
  • 17
  • 35