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
?
This example demonstrates how do I get spinner value in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.
When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event. The AdapterView. OnItemSelectedListener requires the onItemSelected() and onNothingSelected() callback methods. Spinner spinner = (Spinner) findViewById(R.
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());
You have getSelectedXXX methods from the AdapterView class from which the Spinner derives:
getSelectedItem()
getSelectedItemPosition()
getSelectedItemId()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With