RecyclerView Search with Room Database

Yash Prakash
This Code
Published in
2 min readOct 2, 2020

The Recyclerview is the most common and convenient means of displaying rows upon rows of data in our Android apps. Let us look at a common use case in this article — one that concerns with filtering items when you search for keywords in a Room database.

Here, we’re gonna see the simplest method to implement a search functionality in an app which uses Room as the database in these 4 easy steps!

RecyclerView Search Functionality

Let’s get started!

Step 1: Add a menu option and add a method implementing search query in the DAO for the database like this:

Step 2: Add a method in your database Repository and ViewModel classes for completing the MVP model:

Step 3: Add functionality to the search icon with onQueryTextListener in the onCreateOptionsMenu method in your MainActivity class:

MainActivity.kt

Step 4: Finally, write the getItemsFromDb in your MainActivity.kt method to fetch the matching items from the database:

MainActivity.kt

DONE!! Test it out!

The items in the recyclerview will now filter as you type in the searchbox!

Liked the article? Please leave a few claps! Thank you for reading! ❤

Do you want to get one free, clean email from me every week or two weeks containing the best of my curated articles and tutorials that I publish? Join my Codecast!

Connect with me on Twitter and LinkedIn!

--

--

Yash Prakash
This Code

Software engineer → Solopreneur ⦿ Scaling my own 1-person business model ⦿ Writing for busy founders and business owners.