I am using Firebase Firetore in my Android chat app, and i am ordering messages by timestamp which is added as following when a new message is sent:
Map<String, Object> messageMap = new HashMap<>();
...
messageMap.put("timestamp", FieldValue.serverTimestamp());
Here is my code to display all the messages in the chat.
Query firstQuery = FirSingleton.getInstance().mMessages.document(channelFoudId).collection("all_messages")
.orderBy("timestamp", Query.Direction.DESCENDING).limit(limit);
registration = firstQuery.addSnapshotListener(ChatActivity.this, new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e != null) {
Log.i(TAG, "onEvent error: " + e.getMessage());
progressbar.setVisibility(View.GONE);
isLoading = false;
} else {
if (firstTimeLoading) {
lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);
}
for (DocumentChange documentChange : documentSnapshots.getDocumentChanges()) {
if (documentChange.getType() == DocumentChange.Type.ADDED) {
Log.i(TAG, "onEvent: new added");
if (documentChange.getDocument().exists()) {
MessageObject messageObject = documentChange.getDocument().toObject(MessageObject.class);
if (firstTimeLoading) {
//arrayList.add(messageObject);
arrayList.add(0, messageObject);
} else {
arrayList.add(messageObject);
adapter.notifyDataSetChanged();
}
}
}else {
Log.i(TAG, "onEvent: no recently added");
}
}
if (firstTimeLoading){
recyclerView.getAdapter().notifyDataSetChanged();
progressbar.setVisibility(View.GONE);
firstTimeLoading = false;
isLoading = false;
}
}
}
});
The problem is that when the user enters chat activity and there are new messages, the messages are displayed in the opposite order but when refreshing the data (enter the chat activity back) all the messages are in the right order. My question is how to fix this behaviour.