Spinner spinner = ...; // your formidable spinnerString selectValue = "YourValue"; // like a bossspinner.setSelection(((ArrayAdapter<String>)spinner.getAdapter()).getPosition(selectValue));
This code retrieves the position of YourValue in the Spinner's adapter and sets it as the selected item.
Safeguarding your code
Ensure smooth sailing by validating that the selectValue isn't null and the adapter contains items:
if (selectValue != null && spinner.getAdapter().getCount() > 0) { // Null? Ain’t nobody got time for thatint position = ((ArrayAdapter<String>)spinner.getAdapter()).getPosition(selectValue);
if (position >= 0) { // Negative spinner position? Back to Hogwarts, Harry... spinner.setSelection(position);
}
}
This approach fends off NullPointerExceptions and prevents unattainable spinner positions.
Dealing with those special objects
For custom objects, don't forget to override the equals() method:
publicclassYourObject{
private String name;
// Constructor, getters and setters, the usual jazz...@Overridepublicbooleanequals(Object obj){ // Remember, all objects are not created equalif (this == obj) returntrue; // Talkin’ to myself...if (obj == null || getClass() != obj.getClass()) returnfalse;
YourObject that = (YourObject) obj;
return name != null ? name.equals(that.name) : that.name == null; // To be or not to be, that is the question }
}
With a custom adapter, locate and set the position like this:
YourObject selectValue = new YourObject("YourValue"); // Hello, it's me...spinner.setSelection(((ArrayAdapter<YourObject>)spinner.getAdapter()).getPosition(selectValue));
Taking advantage of ArrayList
Leverage ArrayList's functionality and the indexOf method, escaping from the adapter:
ArrayList<String> items = new ArrayList<>(Arrays.asList("Pizza", "Burger", "Sushi", "Salad"));
int position = items.indexOf("Sushi"); // What's cooking, Sushi?spinner.setSelection(position);
This method splits the data handling and view logic, giving you more control.
Syncing with dynamic data
When you're linked with dynamic or database data, sync the Spinner by fetching the value to be selected:
String currentValueFromDB = getCurrentValueFromDatabase(); // "I know Kung-fu." - NeoArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, dynamicValuesFromDB);
spinner.setAdapter(adapter); // new wardrobe for spinnerif (currentValueFromDB != null) {
spinner.setSelection(adapter.getPosition(currentValueFromDB)); // Say my name.}
This show of synchronization keeps Spinner's data and external sources from drifting apart.
Going for simplicity
For readability, try to refrain from overcomplicating. But don't forsake dealing with exceptions or handling unusual scenarios:
/* One does not simply ignore edge cases */
explain-codes/Java/How to set selected item of Spinner by value, not by position?