How to set Spinner Default by its Value instead of Position?

vinothp picture vinothp · May 17, 2012 · Viewed 141k times · Source

I have 1-50 records in the database. I am fetching those data using cursor and set those values to Spinner using Simple Cursor Adapter. Now what i need is i want to set one value say 39th value as default. But not by its position i want to set by its value.

I know how to set the spinner default by its position

   spinner.setSelection(39) 

will set the spinner to that value.

But i didn't have any idea about setting the spinner default by its value(text) in the database. I know the values in the database. For eg "books" is one of the value in the spinner. I need to set the spinner default as books.

Is there any possible way to do this?

Answer

Vinothkumar Arputharaj picture Vinothkumar Arputharaj · May 17, 2012

If you are setting the spinner values by arraylist or array you can set the spinner's selection by using the index of the value.

String myString = "some value"; //the value you want the position for

ArrayAdapter myAdap = (ArrayAdapter) mySpinner.getAdapter(); //cast to an ArrayAdapter

int spinnerPosition = myAdap.getPosition(myString);

//set the default according to value
spinner.setSelection(spinnerPosition);

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