views:

319

answers:

2

Hi everyone, I'm trying to get the selected items string out of a spinner. So far I've got this: bundle.putString(ListDbAdapter.DB_PRI, v.getText().toString());

This doesn'y work and gives a casting exception (I thought you could cast a view to a widget that inherits it... obviously not!). So how do you get the selected value of a spinner

+2  A: 

To get the selected value of a spinner you can follow this example: http://developer.android.com/resources/tutorials/views/hello-spinner.html

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());
Jala
Thanks, this looks great! By nested do you mean in another method (eg onCreate of a new view)?
Matthew Hall
You are welcome. Nested classes: http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
Jala
+2  A: 

You have getSelectedXXX methods from the AdapterView class from which the Spinner derives:

getSelectedItem()

getSelectedItemPosition()

getSelectedItemId()

Rich