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

484,779

Solution 1

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);
}

Solution 2

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.

Solution 3

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.

Solution 4

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.

Solution 5

if you are using string array this is the best way:

int selectionPosition= adapter.getPosition("YOUR_VALUE");
spinner.setSelection(selectionPosition);
Share:
484,779
Pentium10
Author by

Pentium10

Backend engineer, team leader, Google Developer Expert in Cloud, scalability, APIs, BigQuery, mentor, consultant. To contact: message me under my username at gm ail https://kodokmarton.com

Updated on August 20, 2021

Comments

  • Pentium10
    Pentium10 almost 3 years

    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);
    }
    
  • Pentium10
    Pentium10 over 14 years
    There is no other way, you know of?
  • Pentium10
    Pentium10 over 14 years
    How to set selection to nothing? (if the item is not in the list)
  • Dandre Allison
    Dandre Allison about 12 years
    HashMap.get would give better lookup speed than ArrayList.indexOf
  • xbakesx
    xbakesx almost 12 years
    To get rid of the unchecked warning you should use < ? > in your cast instead of <String>. In fact any time you cast anything with a type, you should be using < ? >.
  • ArtOfWarfare
    ArtOfWarfare almost 12 years
    No, if I cast to a < ? > it gives me an error instead of a warning: "The method getPosition(?) in the type ArrayAdapter< ? > is not applicable for the argument (String)."
  • xbakesx
    xbakesx almost 12 years
    Correct, it will then think it's an ArrayAdapter with no type, so it will not assume it's an ArrayAdapter<String>. So to avoid the warning you will need to cast it to ArrayAdapter< ? > then cast the result of your adapter.get() to a String.
  • Soham
    Soham over 11 years
    with a custom adapter you will have to write (override) the code for getPosition()
  • Ajibola
    Ajibola over 11 years
    How about if you are not checking against a string but an element inside an object and it isnt possible to just use the toString() cause the value of the spinner varies from the output of toString().
  • spacebiker
    spacebiker over 10 years
    You forgot to add break; when the index is found to speed up the process.
  • Brad Bass
    Brad Bass over 9 years
    I know this is very old, but this now throws an unchecked call to getPosition(T)
  • ArtOfWarfare
    ArtOfWarfare almost 9 years
    @Dadani - I take it you've never used Python before, because this is stupidly convoluted.
  • Dut A.
    Dut A. almost 9 years
    Agreed, I haven't played around with Python @ArtOfWarfare, but this is a quick way for certain tasks.
  • Manny265
    Manny265 almost 9 years
    had similar errors thrown,but using this old school way helped: stackoverflow.com/questions/25632549/…
  • drearypanoramic
    drearypanoramic over 8 years
    Hmm... Now what if I'm pulling the value from, say, Parse.com, and want to query the user so that the default spinner selection is defaulted to the user's database value?
  • George
    George over 8 years
    @Merrill I am having a similar problem please check if you can be of help on stackoverflow.com/q/35367172/2595059 Thanks
  • Catluc
    Catluc almost 8 years
    why not use do{}while() to avoid using break?
  • Akhil Jain
    Akhil Jain almost 8 years
    @Catluc there are n number of ways to arrive at solution, you choose ...what works best for you
  • ban-geoengineering
    ban-geoengineering almost 8 years
    Rather than 0, you should return -1 if the value is not found - as shown in my answer: stackoverflow.com/a/32377917/1617737 :-)
  • Akhil Jain
    Akhil Jain almost 8 years
    @ban-geoengineering I wrote 0 as backup scenario. If you set -1, what item would be visible at spinner,i suppose the 0th element of spinner adapter, adding -1 also adds overweight of checking whether value is -1 or not, cause setting -1 will cause exception.
  • ban-geoengineering
    ban-geoengineering almost 8 years
    '-1' is the convention in Java for not found, so it is correct to check for -1. In this case, if -1 is detected, then don't call setSelection() - as you could select/show the wrong thing to the user!
  • Steve Rogers
    Steve Rogers over 7 years
    Perfect because don't use ArrayAdapter (which is available at API level 21)
  • Leonardo Sapuy
    Leonardo Sapuy about 7 years
    string.equals(null) usually trhow a NullPointerException when string is null, instead use string!=null to avoid this
  • Graham
    Graham over 6 years
    Welcome to StackOverflow. Answers with only code in them tend to get flagged for deletion as they are "low quality". Please read the help section on answering questions then consider adding some commentary to your Answer.
  • LuFFy
    LuFFy over 6 years
    @user2063903, Please add explanation in your answer.
  • VerumCH
    VerumCH about 6 years
    Returning 0 and returning -1 both have merits. 0 allows you to simply call the function knowing the first item (usually the default) will be set if the passed element isn't found, but makes it harder to respond to an element not being found (since 0 could be a possible index for the element). -1 makes it easy to respond to the element not existing, but also forces you to handle that case. One solution is to change the signature to getIndex(Spinner spinner, String myString, int defaultValue) and then return defaultValue; at the end. This allows either implementation (among others).
  • AZOM
    AZOM about 5 years
    How would this work with localization? In my case the spinner items are localized and like this it breaks for any other language than English. Because spinner.getItemAtPosition(i).toString() returns a localized string, where my comparison value myString expects always English localization (the way String keys are sent to the server)
  • Sunny
    Sunny about 4 years
  • Sasquatch
    Sasquatch over 3 years
    This was very clean, and worked well with view binding. binding.spinner.setSelection(((ArrayAdapter<String>)binding.‌​spinner.getAdapter()‌​).getPosition(pojo.s‌​pinnerValue)); Thanks @A