Ashish Yadav
Ashish Yadav

Reputation: 543

How to put the last document added to the bottom of recyclerview?

Basically I want to align the messages as they are supposed to be in the usual chat app.

Now messages are aligned properly in the RecyclerView. But whenever I send the new message it puts them on the top of the other messages. And whenever I go back and come again to that activity messages are arranged properly(even the top ones).

I just want the message which I send to show up at the bottom. Any help will be appreciated

mLinearLayout.setReverseLayout(true);

Then:

private void loadmessage() {
mFirestore.collection("Users").orderBy("Timestamp", Query.Direction.DESCENDING).limit(10).addSnapshotListener(new EventListener<QuerySnapshot>() {
    @Override
    public void onEvent(@Nullable QuerySnapshot snapshots,
                        @Nullable FirebaseFirestoreException e) {
        if (e != null) {
            Log.w("TAG", "listen:error", e);
            return;
        }

        for (DocumentChange dc : snapshots.getDocumentChanges()) {
            switch (dc.getType()) {
                case ADDED:
                    Message message = dc.getDocument().toObject(Message.class);
                    messageList.add(message);
                    mAdapter.notifyDataSetChanged();
                    mMessagesList.scrollToPosition(messageList.size()-10);
                    break;
            }
        }
    }
});

}

Upvotes: 1

Views: 122

Answers (3)

Ashish Yadav
Ashish Yadav

Reputation: 543

Here is the same case scenario and it has the answer too. So in case anyone looking for the answer. Alex has stated various ways to solve this type of condition.

And This is the github repository for the features of the firestore chat app.

Upvotes: 1

Alex Mamo
Alex Mamo

Reputation: 139019

To solve this, you need to change your query like this:

mFirestore.collection("Users")
    .orderBy("Timestamp", Query.Direction.DESCENDING)
    .limit(10)
    .addSnapshotListener(/* ... */);

And your RecyclerView should look like this:

LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);

This approch will reverse you the order as you want.

Edit:

You can verride the getItem() method to invert the item lookup like this:

@Override
public HashMap getItem(int pos) {
    return super.getItem(getCount() - 1 - pos);
}

Upvotes: 2

Shahzad Afridi
Shahzad Afridi

Reputation: 2158

Try this...

 recyclerView.scrollToPosition(messageList.size()-1);
 mAdapter.notifyDataSetChanged();

Upvotes: 0

Related Questions