I am using Firebase Recycle Adapter to display my messages. I want to display newly received message on top of the recycle view. E.g newly sent/received message by Jfi.. should be on top.
Here is my db structure.
Code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("messages").child(messageSenderId).child(messageReceiverId);
FirebaseRecyclerOptions<ChatMessage> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<ChatMessage>()
.setQuery(query, ChatMessage.class)
.build();
Thanks
you can store the messages into Firebase with a timestamp, then when you retrieve all the data of the message, compare it to the rest of the messages and sort it by the date, and they will display at the top the newest ones, or just invert the RecyclerView
and you will see the latest messages at the top of the RecyclerView
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
myRecyclerView.setLayoutManager(linearLayoutManager);
EDIT
You can compare the values of each message and sort them by the timestamp you get from Firebase
public class timeStampSort implements Comparator<YourModel> {
@Override
public int compare(YourModel o1, YourModel o2) {
return Long.compare(o2.getTimestamp(), o1.getTimestamp());
}
}
and then before calling mAdapter = new MessagesAdapter....
do this
Collections.sort(yourArray, new timeStampSort());
That should order your messages with the timestamp from each one without having to invert the RecyclerView
The above sort can be done if you already made another orderByChild in your query and you can't do more than once.
But, as Frank suggests, it's much more efficient to do it with orderByChild
, so you can only do this
Query query = rootRef.child("messages").child(messageSenderId).child(messageReceiverId).orderByChild("timestamp");