Stop Using RecyclerView.Adapter

Migrate to ListAdapter for your RecyclerView in 3 simple steps.

Nishant Aanjaney Jalan
CodeX

--

Photo by Glenn Carstens-Peters on Unsplash

There are only 3 easy steps to migrate your RecyclerView.Adapter class to a ListAdapter.

Why and when should I migrate?

When you have a recycler view that requires constantly changing over time, you need to use a ListAdapter. By default, the RecyclerView implementation of changing the list items is inefficient. As developers, we need to look for efficient solutions.

What is DiffUtil?

Google came up with a class called DiffUtil that compares the currently existing list with the newly submitted list; it changes the necessary UI on the screen only. However, this was adding to the already elaborate boilerplate code and hence, we can use a ListAdapter for reducing the boilerplate.

#0 — Getting Started

This is your traditional RecyclerView Adapter that you see here. We shall modify this class to use ListAdapter instead.

#1 — Create the DiffUtil Callback

As stated earlier, we need to use the DiffUtil so that we compare the lists efficiently.

We can start by creating a static anonymous object of the interface. We have two functions here:

  1. areItemsTheSame — This function returns true if the items that we are comparing are the same. We usually do this by comparing the Primary Key of the modals.
  2. areContentsTheSame — This function returns true if the other properties of the items are the same. This checks whether there are any internal changes within the item itself.

#2 — Replace the Inherited Class

Now we can replace the RecyclerView.Adapter to the ListAdapter.

We pass the object of the DiffUtil in the parent constructor. We have successfully migrated our class to a ListAdapter; however, our code is still not what we need yet.

#3 — Adding the final touches.

Now that you are using ListAdapter, it makes sense to leverage the power we get from it.

  1. You can remove the getItemCount function. ListAdapter implements that for you.
  2. Replace the list property as shown below.
  3. Change list[position] to getItem(position).

Conclusion

With a few minor changes, and following these 3 simple steps, you can improve the performance of your application significantly. ListAdapter uses the RecyclerView.Adapter inherently and made it better performant. If your list varies continuously, then using a ListAdapter is always a good preference.

I hope you enjoyed reading my article and learnt something. Thank you! ✌️

Want to connect?My GitHub profile.
My Portfolio website.

--

--

Nishant Aanjaney Jalan
CodeX
Editor for

Undergraduate Student | CS and Math Teacher | Android & Full-Stack Developer | Oracle Certified Java Programmer | https://cybercoder-naj.github.io