Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set selected item of Spinner by value, not by position?

I have a update view, where I need to preselect the value stored in database for a Spinner.

I was having in mind something like this, but the Adapter has no indexOf method, so I am stuck.

void setSpinner(String value)
{
    int pos = getSpinnerField().getAdapter().indexOf(value);
    getSpinnerField().setSelection(pos);
}
like image 249
Pentium10 Avatar asked Mar 05 '10 21:03

Pentium10


4 Answers

Suppose your Spinner is named mSpinner, and it contains as one of its choices: "some value".

To find and compare the position of "some value" in the Spinner use this:

String compareValue = "some value";
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
if (compareValue != null) {
    int spinnerPosition = adapter.getPosition(compareValue);
    mSpinner.setSelection(spinnerPosition);
}
like image 157
Merrill Avatar answered Nov 12 '22 02:11

Merrill


A simple way to set spinner based on value is

mySpinner.setSelection(getIndex(mySpinner, myValue));

 //private method of your class
 private int getIndex(Spinner spinner, String myString){
     for (int i=0;i<spinner.getCount();i++){
         if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString)){
             return i;
         }
     }

     return 0;
 } 

Way to complex code are already there, this is just much plainer.

like image 30
Akhil Jain Avatar answered Nov 12 '22 02:11

Akhil Jain


Based on Merrill's answer, I came up with this single line solution... it's not very pretty, but you can blame whoever maintains the code for Spinner for neglecting to include a function that does this for that.

mySpinner.setSelection(((ArrayAdapter<String>)mySpinner.getAdapter()).getPosition(myString));

You'll get a warning about how the cast to a ArrayAdapter<String> is unchecked... really, you could just use an ArrayAdapter as Merrill did, but that just exchanges one warning for another.

If the warning causes issue, just add

@SuppressWarnings("unchecked")

to the method signature or above the statement.

like image 39
ArtOfWarfare Avatar answered Nov 12 '22 00:11

ArtOfWarfare


I keep a separate ArrayList of all the items in my Spinners. This way I can do indexOf on the ArrayList and then use that value to set the selection in the Spinner.

like image 36
Mark B Avatar answered Nov 12 '22 02:11

Mark B