Reputation: 3593
New to Android, I got a simple application with spinners and associated ArrayAdapters working: when things get selected, I seem to be able and trigger some calculations. I am then saving the current selected item.
At some point, I retrieve the saved value, and want to position the spinner at that value: basically setPosition() the spinner to that object.
I have found lots of tutorials with the same format I have: use the getPosition() on the ArrayAdapter, and pass in the object you are looking for... Trouble is, it keeps returning -1 (not found).
Debugging, I have verified that the object I pass is not null, and so is the ArrayAdapter, and also the ArrayAdapter getCount returns me the items it should have (so it's not empty).
I'm at loss. Appreciate any... pointers? :-)
/* ArrayAdapter class looks like this*/
public class MyAdapter extends ArrayAdapter<MyClass> {
// Constructor
MyAdapter(@NonNull Context context, int resource, @NonNull List<MyClass> objects) {
super(context, resource, objects);
}
}
/* Fragment looks like this*/
final MyAdapter mAdapter = new MyAdapter(
requireActivity(),
android.R.layout.simple_spinner_item,
objects);
Spinner mySpinner = fragment_view.findViewById(R.id.my_spinner);
mySpinner.setAdapter(mAdapter);
// assume I have one "object" of MyClass,
// and want to search for it in "MyAdapter"
int spinnerPosition = mAdapter.getPosition(objectToBeFound); // returns -1
mySpinner.setSelection(spinnerPosition);
Upvotes: 1
Views: 1917
Reputation: 37404
Adapter internally works with List
public int getPosition(@Nullable T item) {
return mObjects.indexOf(item);
}
so getPosition
internally depends upon List#indexOf(T)
and which relies on equals
method
(o==null ? get(i)==null : o.equals(get(i)))
so you are getting -1
because you haven't implemented equals
and hashcode
method properly in MyClass
so implement both methods and you will be able to get the precise index.
Referene:
difference between equals() and hashCode()
Upvotes: 4