How to set selected item of Spinner by value, not by position?
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);
![Pentium10](https://i.stack.imgur.com/gInNr.png?s=256&g=1)
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, 2021Comments
-
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 noindexOf
method, so I am stuck.void setSpinner(String value) { int pos = getSpinnerField().getAdapter().indexOf(value); getSpinnerField().setSelection(pos); }
-
Pentium10 over 14 yearsThere is no other way, you know of?
-
Pentium10 over 14 yearsHow to set selection to nothing? (if the item is not in the list)
-
Dandre Allison about 12 yearsHashMap.get would give better lookup speed than ArrayList.indexOf
-
xbakesx almost 12 yearsTo 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 almost 12 yearsNo, 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 almost 12 yearsCorrect, 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 over 11 yearswith a custom adapter you will have to write (override) the code for getPosition()
-
Ajibola over 11 yearsHow 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 over 10 yearsYou forgot to add
break;
when the index is found to speed up the process. -
Brad Bass over 9 yearsI know this is very old, but this now throws an unchecked call to getPosition(T)
-
ArtOfWarfare almost 9 years@Dadani - I take it you've never used Python before, because this is stupidly convoluted.
-
Dut A. almost 9 yearsAgreed, I haven't played around with Python @ArtOfWarfare, but this is a quick way for certain tasks.
-
Manny265 almost 9 yearshad similar errors thrown,but using this old school way helped: stackoverflow.com/questions/25632549/…
-
drearypanoramic over 8 yearsHmm... 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 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 almost 8 yearswhy not use do{}while() to avoid using break?
-
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 almost 8 yearsRather than
0
, you should return-1
if the value is not found - as shown in my answer: stackoverflow.com/a/32377917/1617737 :-) -
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 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 callsetSelection()
- as you could select/show the wrong thing to the user! -
Steve Rogers over 7 yearsPerfect because don't use ArrayAdapter (which is available at API level 21)
-
Leonardo Sapuy about 7 yearsstring.equals(null) usually trhow a NullPointerException when string is null, instead use string!=null to avoid this
-
Graham over 6 yearsWelcome 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 over 6 years@user2063903, Please add explanation in your answer.
-
VerumCH about 6 yearsReturning
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 togetIndex(Spinner spinner, String myString, int defaultValue)
and thenreturn defaultValue;
at the end. This allows either implementation (among others). -
AZOM about 5 yearsHow 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 valuemyString
expects always English localization (the way String keys are sent to the server) -
Sunny about 4 yearsstackoverflow.com/questions/61790242/spinner-data-from-server can anyone help me out
-
Sasquatch over 3 yearsThis was very clean, and worked well with view binding. binding.spinner.setSelection(((ArrayAdapter<String>)binding.spinner.getAdapter()).getPosition(pojo.spinnerValue)); Thanks @A