Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the selected value of a Spinner?

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?

like image 257
Matthew Hall Avatar asked Apr 16 '10 11:04

Matthew Hall


People also ask

How do I get spinner values?

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.

Which function is used to get the selected item from the spinner?

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.


2 Answers

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()); 
like image 81
jalopaba Avatar answered Sep 17 '22 18:09

jalopaba


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

getSelectedItem()

getSelectedItemPosition()

getSelectedItemId()

like image 26
Rich Avatar answered Sep 16 '22 18:09

Rich