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

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


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 forArrayAdapter myAdap = (ArrayAdapter) mySpinner.getAdapter(); //cast to an ArrayAdapterint spinnerPosition = myAdap.getPosition(myString);//set the default according to valuespinner.setSelection(spinnerPosition);

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


Finally, i solved the problem by using following way, in which the position of the spinner can be get by its string

private int getPostiton(String locationid,Cursor cursor){    int i;    cursor.moveToFirst();     for(i=0;i< cursor.getCount()-1;i++)    {          String locationVal = cursor.getString(cursor.getColumnIndex(RoadMoveDataBase.LT_LOCATION));          if(locationVal.equals(locationid))        {             position = i+1;              break;        }        else        {            position = 0;        }        cursor.moveToNext();      } 

Calling the method

    Spinner location2 = (Spinner)findViewById(R.id.spinner1);    int location2id = getPostiton(cursor.getString(3),cursor);    location2.setSelection(location2id);

I hope it will help for some one..


Compare string with value from index

private void selectSpinnerValue(Spinner spinner, String myString)     {         int index = 0;         for(int i = 0; i < spinner.getCount(); i++){             if(spinner.getItemAtPosition(i).toString().equals(myString)){                 spinner.setSelection(i);                 break;             }         }     }