Explain Codes LogoExplain Codes Logo

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

java
spinner
arraylist
nullpointerexception
Nikita BarsukovbyNikita Barsukov·Aug 11, 2024
TLDR

Quickly select a value in a Spinner:

Spinner spinner = ...; // your formidable spinner String selectValue = "YourValue"; // like a boss spinner.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 that int 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:

public class YourObject { private String name; // Constructor, getters and setters, the usual jazz... @Override public boolean equals(Object obj) { // Remember, all objects are not created equal if (this == obj) return true; // Talkin’ to myself... if (obj == null || getClass() != obj.getClass()) return false; 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." - Neo ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, dynamicValuesFromDB); spinner.setAdapter(adapter); // new wardrobe for spinner if (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 */