Skepller
Skepller

Reputation: 144

Filter RecyclerView by value inside object

I have a RecyclerView that returns a list of objects to a fragment, I want the fragment to only show objects that has a specific value in one of their variables. How can I do that?

This is how I call my adapter on the fragment:

RecyclerView recyclerview = view.findViewById(R.id.list);

if (recyclerview != null) {
    Context context = view.getContext();
    adapter = new MyHospitalHistoryRecyclerViewAdapter(DummyContent.ITEMS, mListener);
    recyclerview.setAdapter(adapter);
}

return view;

DummyContent.ITEMS is the DummyItems-type list.

Does anyone know how I can do this? I have tested everything I know

Upvotes: 1

Views: 672

Answers (1)

S-Sh
S-Sh

Reputation: 3883

Try add filter logic in the adapter, for example:

class MyAdapter extends RecyclerView.Adapter<MyViewHolder> implements Filterable {
      private NewFilter mFilter = new NewFilter();
      private List<MyData> mItems;
      private List<MyData> mFiltered = new ArrayList<>();     // <--- use this collection in all required getItemsCount and onBindViewHolder methods

      @Override
      public Filter getFilter {
            return mFilter;
      }

      public class NewFilter extends Filter {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {
                mFiltered .clear();
                final FilterResults results = new FilterResults();
                if(charSequence.length() == 0){
                    mFiltered .addAll(mItems);
                }else{
                    final String filterPattern =charSequence.toString().toLowerCase().trim();
                    for(MyData item: mItems) {
                        if(item.getMyProperty().toLowerCase().contains(filterPattern)){ // replace this condition with actual you need
                            mFilteredItems.add(item);
                        }
                    }
                }
                results.values = mFilteredItems;
                results.count = mFilteredItems.size();
                return results;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                this.mAdapter.notifyDataSetChanged();
            }
        }

Then you can use it in fragment with just:

adapter.getFilter().filter("hello");

The line above updates the list with only items that contain 'hello' in 'myProperty' property.

Upvotes: 1

Related Questions