RecyclerView filter not working

丶灬走出姿态 提交于 2019-12-05 20:21:48

assuming contactsList is var with the full contacts

    private List<Contact> filter(List<Contact> models, String query) {
    query = query.toLowerCase();
    if(query.equals("")) { return contactsList; }

    final List<Contact> filteredModelList = new ArrayList<>();
    for (Contact model : models) {
        final String text = model.name.toLowerCase();
        if (text.contains(query)) {
            filteredModelList.add(model);
        }
    }
    return filteredModelList;
}

He has defined in this way:

public void setModels(List<ExampleModel> models) {
    mModels = new ArrayList<>(models);
}

Initialize like the way he has done.

Your soultion would be:

this.contactsList = new ArrayList<>(contactsList);

You need to move your filter() method from your Activity to your Adapter. At your Adapter add one additional variable to hold a copy of unfiltered dataset. In your case, you need contactsList and copyOfContactsList variables.

Change your Adapter's constructor as follows:

public class ContactsAdapter extends RecyclerView.Adapter<ContactViewHolder> {

    ....
    private ArrayList<Contact> contactsList = new ArrayList<>();
    private ArrayList<Contact> copyOfContactsList = new ArrayList<>();
    ....

    public ContactsAdapter(Context context, ArrayList<Contact> dataSet, boolean fromMyContacts){
        ...
        this.contactsList = dataSet;
        copyOfContactsList.addAll(dataSet);
        ...
    }

and this is the filter method to be added to your Adapter:

public void filter(String text) {
    if(text.isEmpty()){
        contactsList.clear();
        contactsList.addAll(copyOfContactsList);
    } else{
        ArrayList<Contact> result = new ArrayList<>();
        text = text.toLowerCase();
        for(Contact item: copyOfContactsList){
            if(item.getName().toLowerCase().contains(text)){
                result.add(item);
            }
        }
        contactsList.clear();
        contactsList.addAll(result);
    }
    notifyDataSetChanged();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!