Android Spinner set Selected Item by Value

The spinner provides a way to set the selected valued based on the position using the setSelection(int position) method. Now to get the position based on a value you have to loop thru the spinner and get the position. Here is an example
mySpinner.setSelection(getIndex(mySpinner, myValue));

 private int getIndex(Spinner spinner, String myString){

  int index = 0;

  for (int i=0;i<spinner.getCount();i++){
   if (spinner.getItemAtPosition(i).equals(myString)){
    index = i;
   }
  }
  return index;
 }
If you are using an ArrayList for your Spinner Adapter then you can use that to loop thru and get the index. Another way is is to loop thru the adapter entries
Spinner s = (Spinner) findViewById(R.id.spinner_id);
for(i=0; i < adapter.getCount(); i++) {
  if(myString.trim().equals(adapter.getItem(i).toString())){
    s.setSelection(i);
    break;
  }
}

9 comments :

  1. Thanks a lot!! First solution worked for me perfectly.. :)

    ReplyDelete
  2. Thanks for your code.... you saved my day... perfectly works for me :)

    ReplyDelete
  3. The second method isn't working. For some reason can't use i in the if statement after the for statement. ?????

    Thanks!

    ReplyDelete
  4. Very useful and simple to import, thanks you!!!

    ReplyDelete
  5. Thanks, used your first snippet
    Omar

    ReplyDelete
  6. Thanks a lot, very useful and work for me.

    ReplyDelete
  7. Thanks a lot, what a method to implement, very powerful code to implement dynamic values to set on spinner without any hassle. Kudos and thank you!!!

    ReplyDelete
  8. These methods don't work

    ReplyDelete
  9. This method work. Thank you very much

    ReplyDelete