I have an ArrayAdapter (myAdapter) attached to an AutoCompleteTextView (textView) component.
Once the user presses a character I would like to populate AutoCompleteTextView\
I had the exact same problem. After examining the ArrayAdapter and AutoCompleteTextView source code, I found out that the problem was, in short, that:
ArrayAdapter.mObjects
.AutoCompleteTextView
enables ArrayAdapter
's filtering, meaning that new objects are added to ArrayAdapter.mOriginalValues
, while mObjects
contains the filtered objects.ArrayAdapter.getCount()
always returns the size of mObjects
.My solution was to override ArrayAdapter.getFilter()
to return a non-filtering filter. This way mOriginalValues
is null
and mObjects
is used instead in all cases.
Sample code:
public class MyAdapter extends ArrayAdapter {
NoFilter noFilter;
/*
...
*/
/**
* Override ArrayAdapter.getFilter() to return our own filtering.
*/
public Filter getFilter() {
if (noFilter == null) {
noFilter = new NoFilter();
}
return noFilter;
}
/**
* Class which does not perform any filtering.
* Filtering is already done by the web service when asking for the list,
* so there is no need to do any more as well.
* This way, ArrayAdapter.mOriginalValues is not used when calling e.g.
* ArrayAdapter.add(), but instead ArrayAdapter.mObjects is updated directly
* and methods like getCount() return the expected result.
*/
private class NoFilter extends Filter {
protected FilterResults performFiltering(CharSequence prefix) {
return new FilterResults();
}
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Do nothing
}
}
}