Skip to content Skip to sidebar Skip to footer

Filter In Listview Did Not Filter From The Full List, But From Already Filtered List

I have an listview with filter. When I input some words in an edittext that I used as a filter for example 'david', it works well, items in the list are filtered and it will show a

Solution 1:

You need two different lists for filtering, so try change mOriginalList = mFilteredList; to mOriginalList = new ArrayList<>(mFilteredList); may solve the issue.

Explanations:

mOriginalList = mFilteredList; is same list with two different names. It is helpful in modular program, just like mFilteredList = oobjects; in your adapter constructor.

mOriginalList = new ArrayList<>(mFilteredList); is to make a shallow copy of mFilteredList and store it as mOriginalList, so the lists are different.

Shallow and Deep Copy:

Example: If your custom class, Registrant, contains a public field (List, Map or custom object etc., that requires new for creation) named sample. Under shallow copy, mOriginalList = new ArrayList<>(mFilteredList);, mOriginalList.get(i) is a copy of mFilteredList.get(i) and they are 2 different Registrant objects. But mOriginalList.get(i).sample and mFilteredList.get(i).sample is the same object.

If you need mOriginalList.get(i).sample and mFilteredList.get(i).sample to be different objects, then it is called deep copy. There is no ready method to make deep copy, you have to make your own method according to your custom class. But up to now, I never have a case that needs deep copy.

Hope that helps!

Solution 2:

You should keep two separate lists in your adapter such as,

private List<Registrant> mOriginalList = newArrayList();
private List<Registrant> mFilteredList = newArrayList();

publicWRegistrantListAdapter(Context context, int resource, ArrayList<Registrant> oobjects, int workshopItemId) {
    super(context, resource, oobjects);
    mContext = context;
    mResource = resource;
    mFilteredList.addAll(oobjects);
    mOriginalList.addAll(oobjects);
}

Initially, both of them should have the same value and you will use filteredList for showing your data. Later in the filter, you should publish your data like

@Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                filteredList.clear();
                filteredList.addAll((ArrayList<Registrant>) results.values);
                notifyDataSetChanged();
            }

A complete example is can be found in Filter ListView with arrayadapter

Post a Comment for "Filter In Listview Did Not Filter From The Full List, But From Already Filtered List"