Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show empty view with Paging 3 library in Android

I want to show empty view when paging3 is loaded with an empty list.

It seems to work with following code. Is this the proper way to do with the paging 3 library?:

        adapter?.addLoadStateListener { loadState ->
            adapter?.apply {
                if (itemCount <= 0 && !loadState.source.refresh.endOfPaginationReached) {
                    Timber.d("==> to show empty view")
                    tvEmptyView.isGone = false
                } else {
                    Timber.d("==> to hide empty view")
                    tvEmptyView.isGone = true
                }
            }
        } 
like image 967
Eric Cen Avatar asked Sep 04 '20 21:09

Eric Cen


People also ask

How can I get data from PagingData?

Display the paged data in your UI Create an instance of your PagingDataAdapter class. Pass the PagingDataAdapter instance to the RecyclerView list that you want to display your paged data. Observe the PagingData stream, and pass each generated value to your adapter's submitData() method.

What is paging Library in Android?

The Paging Library lets you load data directly from your backend using keys that the network provides. Your data can be uncountably large. Using the Paging Library, you can load data into pages until there isn't any data remaining. You can observe your data more easily.

What is paging data?

Paging library overview Part of Android Jetpack. The Paging library helps you load and display pages of data from a larger dataset from local storage or over network. This approach allows your app to use both network bandwidth and system resources more efficiently.


2 Answers

This worked for me:

if (loadState.source.refresh is LoadState.NotLoading &&
    loadState.append.endOfPaginationReached &&
    adapter.itemCount < 1
) {
   recyclerView.isVisible = false
   textViewEmpty.isVisible = true
} else {
    textViewEmpty.isVisible = false
}
like image 191
Florian Walther Avatar answered Oct 07 '22 13:10

Florian Walther


You can directly plug into the adapter loadStateFlow, e.g

    lifecycleScope.launchWhenCreated {
        @OptIn(ExperimentalCoroutinesApi::class)
        adapter.loadStateFlow.collectLatest { loadStates ->
            val refresher = loadStates.refresh
            val displayEmptyMessage =  (refresher is LoadState.NotLoading && refresher.endOfPaginationReached && adapter.itemCount == 0)
            layoutBinding.emptyStateMessage.isVisible = displayEmptyMessage
            layoutBinding.emptyStateImage.isVisible = displayEmptyMessage
            layoutBinding.swipeToRefresh.isRefreshing = refresher is LoadState.Loading
        }
    }
like image 43
Paul Okeke Avatar answered Oct 07 '22 15:10

Paul Okeke