How do you get the selected value of a Spinner?

Matthew Hall picture Matthew Hall · Apr 16, 2010 · Viewed 149.6k times · Source

I am trying to get the selected items string out of a Spinner. So far I have gotten this:

bundle.putString(ListDbAdapter.DB_PRI, v.getText().toString());

This does not work and gives a class casting exception (I thought I could cast a View to a widget that inherits it. Obviously not!) So how do you get the selected value of a Spinner?

Answer

jalopaba picture jalopaba · Apr 16, 2010

To get the selected value of a spinner you can follow this example.

Create a nested class that implements AdapterView.OnItemSelectedListener. This will provide a callback method that will notify your application when an item has been selected from the Spinner.

Within "onItemSelected" method of that class, you can get the selected item:

public class YourItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        String selected = parent.getItemAtPosition(pos).toString();
    }

    public void onNothingSelected(AdapterView parent) {
        // Do nothing.
    }
}

Finally, your ItemSelectedListener needs to be registered in the Spinner:

spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());