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);
}
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);
}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With