Pagination with Room Database

Updated 15 February 2022

Save

In today’s article, we are going to learn how we can use pagination with room database using jetpack’s paging library.

Pagination allows us to load and display a small amount of data at a time.

Why Pagination is important?

In a typical application when we load products there may be infinitely large products/data that we cannot load all at once.

If we do so it will consume more resources and the application will start to lag and in the worst-case application may go into NOT RESPONDING state.

We are going to load data from the network, save that data into a database, and finally fetch data from the database.

Important components for Paging

  1. Paged List
  2. Data Source
  3. PagedListAdapter

PagedList: A PagedList is a List which loads its data in chunks (pages) from a DataSource. Items can be accessed with get(int), and further loading can be triggered with loadAround(int)

Data Source:

From the related DataSource object, PagedList loads an up-to-date snapshot of our app data. PagedList receives data from the backend or app database. RecyclerView is used to display standard data in RecyclerView.

PagedListAdapter: PagedListAdapter is used to load items into RecyclerView when showing PagedList data.

Let’s get started.

1. Add dependency

2.  Create a DataSource.Factory in DAO for getting data which we are going to supply to PagedList

3. In order to retrieve the data we are going to create a repository and from that repo, we will get our data as a paged list.

4. In order to show data in recycler we are going to need an adapter, and we are going to use a PagedListAdapter to show paged list data.

areContentsTheSame: Called by the DiffUtil when it wants to check whether two items have the same data. DiffUtil uses this information to detect if the contents of an item have changed.

areItemsTheSame: Called by the DiffUtil to decide whether two objects represent the same Item.

5. Finally, set items in recycler view and show.

That’s it.

Conclusion

In this article, we learned how we can use pagination with a room database. We also learned why it is necessary to use pagination.

Head over here to learn more about android programming.

Referneces:

https://medium.com/nerd-for-tech/jetpack-paging-library-in-android-with-room-database-39e6392c3c47

https://developer.android.com/codelabs/android-paging?index=..%2F..%2Findex#0

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home