I have been banging my head against this one for two days on and off.
I tried to use getfilter.filter() but it didn’t work. so I created this code to search a list. it works but when I delete some letters the list gets stuck at the last result and never updates.
eg list: hello, hi, han, solo
when i type ‘h’ then hello, hi, and han show up.
when i add an ‘e’ so thats its ‘he’ only hello shows
when i delete the e, han and hi do not come up again.
private TextWatcher filterTextWatcher = new TextWatcher() {
final ArrayList<String> finalItems = mItems;
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
ArrayList<String> searchedItems = retainsSearched(mItems, s.toString());
adapter.clear();
for (int i = 0; i < searchedItems.size(); i++) {
adapter.add(searchedItems.get(i));
}
adapter.notifyDataSetChanged();
}
};
public ArrayList<String> retainsSearched(ArrayList<String> mItems2, String term) {
ArrayList<String> stations = new ArrayList<String>();
for (int i = 0; i < mItems2.size(); i++) {
if (mItems2.get(i).toLowerCase().startsWith(term.toLowerCase())) {
stations.add(mItems2.get(i));
}
}
return stations;
}
That is most likely happening because the
mItemslist that you use in theTextWatcheris the list that is backing your adapter so by modifying it(when filtering and clearing/re adding items in the adapter) you always reduce the number of items available in the adapter, the items that you “see” each time you filter the list.Instead try to make a copy of your initial items(
mItemslist) in the adapter and always do the filtering by testing the items in that copy(but don’t modify it, just add the matched items to the adapter).Again, you should use the
getFilter()method.Edit: