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
- Paged List
- Data Source
- 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
1 2 3 4 5 6 7 8 9 |
// room def room_version = "2.4.1" implementation "androidx.room:room-ktx:$room_version" implementation "androidx.room:room-runtime:$room_version" kapt "androidx.room:room-compiler:$room_version" implementation "androidx.room:room-paging:$room_version" // paging implementation 'androidx.paging:paging-runtime-ktx:3.1.0' |
2. Create a DataSource.Factory in DAO for getting data which we are going to supply to PagedList
1 2 |
@Query("SELECT * FROM user") fun getUsers(): DataSource.Factory<Int, User> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
object UserRepository { fun getPagedList(application: Application): LiveData<PagedList<User>> { val factory = AppDatabase.getInstance(application.applicationContext).userDao().getUsers() return LivePagedListBuilder<Int, User>( factory, PagedList .Config .Builder() .setPageSize(10) .setPrefetchDistance(2) .setEnablePlaceholders(false) .build() ).build() } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class UserRVAdapter : PagedListAdapter<User, UserRVAdapter.ViewHolder>(DIFF_CALLBACK) { inner class ViewHolder(val binding: ItemUserBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserRVAdapter.ViewHolder { return ViewHolder(ItemUserBinding.inflate(LayoutInflater.from(parent.context))) } override fun onBindViewHolder(holder: UserRVAdapter.ViewHolder, position: Int) { holder.binding.user = getUser(position) holder.binding.executePendingBindings() } private fun getUser(position: Int): User? { return getItem(position) } companion object { val DIFF_CALLBACK = object : DiffUtil.ItemCallback<User>() { override fun areItemsTheSame(oldItem: User, newItem: User): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: User, newItem: User): Boolean { return oldItem.id == newItem.id } } } } |
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.
1 2 3 4 5 6 7 8 |
val adapter = UserRVAdapter() val model = ViewModelProvider.AndroidViewModelFactory.getInstance(application) .create(UserViewModel::class.java) model.fetchPagedUsers().observe(this, Observer { adapter.submitList(it) recyclerView.adapter = adapter }) |
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