I have an EditText component that searches a list using a custom adapter. It works fine except that the filtered views remain on screen. If the user deletes all the text in the edit box, I would like the full list to return to the screen.
I’ve tried three approaches:
-
I put a condition in my adapter’s filter classs. Placeing
notifyDataSetChanged();in FilterResults function, and it crashes the program. -
Detecting if the EditTtext box is empty in the Activity, and then calling
notifyDataSetChanged();. The condition works because I seeSystem.out.println()prints text to the console. but it has no effect on the listView. Only the filtered text remains on screen. -
Placing
notifyDataSetChanged();inOnTextChanged(). This also has no effect on resetting the listview.
How do I get the listview to reset when the EditText Box is empty?
Code from Activity:
// in OnCreate
if (searchBox.toString().equals("")){
objAdapter.notifyDataSetChanged();
}
searchBox.addTextChangedListener(new TextWatcher(){
@Override
public void afterTextChanged(Editable arg0) {
// Do nothing
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Do nothing
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
objAdapter.getFilter().filter(s);
if (s.toString().equals("")){
// objAdapter.notifyDataSetChanged(); fails here
}
}
}
});
Code from Adapter.
public class NewsRowAdapter extends ArrayAdapter<Item> {
//.... code
private class ListFilter extends Filter
{
@Override
protected FilterResults performFiltering(CharSequence constraint)
{
FilterResults results = new FilterResults();
String prefix = constraint.toString().toLowerCase();
if (prefix == null || prefix.length() == 0)
{
System.out.println("editText is empty");
// notifyDataSetChanged(); no effect
ArrayList<Item> list = new ArrayList<Item>(original);
results.values = list;
results.count = list.size();
}
else
{
final ArrayList<Item> list = original;
int count = list.size();
final ArrayList<Item> nlist = new ArrayList<Item>(count);
for (int i=0; i<count; i++)
{
final Item pkmn = list.get(i);
final String value = pkmn.getName().toLowerCase();
if (value.startsWith(prefix))
{
nlist.add(pkmn);
}
}
results.values = nlist;
results.count = nlist.size();
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
fitems = (ArrayList<Item>)results.values;
clear();
int count = fitems.size();
for (int i=0; i<count; i++)
{
Item pkmn = (Item)fitems.get(i);
add(pkmn);
}
if (fitems.size() > 0){
notifyDataSetChanged();
} else{
notifyDataSetInvalidated();
}
}
}
Instead of
searchBox.toString(), usesearchBox.getText().toString()searchBox.toString()is returning the object’s VM reference — which will never equal nothing