Home » Android » java – How to make Paging library work with reverse recyclerview?

java – How to make Paging library work with reverse recyclerview?

Posted by: admin May 14, 2020 Leave a comment


How to use the latest paging with endless reverse recyclerview for the purpose of chat?

I have linear layout with reverse layout true:

LinearLayoutManager layoutManager = new LinearLayoutManager(this);

and inside scroll listener :

public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    super.onScrolled(recyclerView, dx, dy);
    int visibleItemCount = layoutManager.getChildCount();
    int totalItemCount = layoutManager.getItemCount();
    int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

    if (!isLoading && !isLastPage) {
        if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                && firstVisibleItemPosition >= 0
                && totalItemCount >= PAGE_SIZE) {

The query for fetching messages:

SELECT * FROM Message WHERE chatId = :chatId ORDER BY dbId ASC

Used for the room like below;

@Query("SELECT * FROM Message WHERE chatId = :chatId ORDER BY dbId ASC")
DataSource.Factory<Integer,Message> fetchAll(String chatId);

The problem is that if I use ASC in the query, the list is automatically scrolling and fetching other messages. if used DESC, then message list is not coming in order.

Can anyone please help?

How to&Answers:

I think it’s enogh



If you have an incremental list in room database (line an index/contor) you can sort it after it in DESC mode


It may be late but yes I too was making a chat application where the chat should open at the bottom and the person can scroll up to see old messages. I have used room DB to store chat messages and used the pagination library for pagination. For this functionality to achieve you have to use only


and use room datasource factory with the following command to fetch the data –

    @Query("SELECT * from table_name ORDER BY timestamp DESC")

Here order by desc is very important. The timestamp is the field in the database table.
And u don’t need scroll listener with pagination library. It automatically handles the scrolling listeners.
For the whole project refer this – https://bitbucket.org/raghavsharma29/chatbotmvvm/src/dev/