Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Paging library work with reverse recyclerview?

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);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);

and inside scroll listener :

@Override
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) {
            loadMoreItems();
        }
    }
}

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?

like image 725
krupal.agile Avatar asked May 16 '18 13:05

krupal.agile


2 Answers

I think it's enogh

layoutManager.setStackFromEnd(false);


layoutManager.setReverseLayout(true);

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

like image 137
Victor Radulescu Avatar answered Oct 23 '22 06:10

Victor Radulescu


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

`app:reverseLayout="true"`

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/

like image 1
Raghav Sharma Avatar answered Oct 23 '22 07:10

Raghav Sharma