Filtering data in RecyclerViews

This post will show how to filter through a list of data that’s set in a RecyclerView.

A lot of apps have a search feature where you have a list in a RecyclerView and a Search menu bar where as the user types, the list filters automatically. I wrote a whole post on how to build a custom search view in one of my posts. Thankfully, this guide will be more brief and straightforward.

The main library that we’ll be utilizing is the same SearchView library that we used in my Custom SearchView post, MaterialSearchView.

Except this time, we’ll be using this directly in the screen where you have your RecyclerView with the list of data.

First, follow the directions of that MaterialSearchView library to set up your menu bars.

Second, in your activity or fragment, set the on query text listener on your search view like this.

If you’re observant, you’ll see that we call two methods sequentially, getFilter and filter on my RecyclerView.Adapter (variable named mAdapter). We have a method on my adapter called setData and we use that to set our data. I’ll go over the getFilter and filter methods first.

getFilter && filter

First thing we want to do is to implement Filterable on our RecyclerView.Adapter

There are a few things going on here. First, we implement Filterable to our adapter and implement the necessary methods getFilter and getFilteredResults. What these two basically do is take in a string (which is passed in from our activity which is bound to the user inputs in our SearchView), and filters through the data list. It scopes down the data based on the filtering conditions we give it, and returns the result. This implements the actual filtering feature that works with the filter method we have in our mAdapter.getFilter().filter(newText) method chain.

One important thing that we do in our activity though is when the user input is empty. If you look at the listeners that I set on our SearchView, you’ll see that I constantly set the dataset in our RecyclerView back with the full data set. The reason for this is because the data set in our adapter will be reduced as the user searches through. Thus, we want to “reset” our list of data back up to full when the user either deletes some of his/her input to search for something else or clears the input in the SearchView entirely.

Pretty straightforward right?