我在Android聊天应用程序中使用Firebase Firetore,并且我按时间戳订购消息,当发送新消息时,时间戳添加如下:
Map<String, Object> messageMap = new HashMap<>();
...
messageMap.put("timestamp", FieldValue.serverTimestamp());
这是我的代码,用于显示聊天中的所有消息。
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;
}
}
}
});
问题在于,当用户进入聊天活动并且有新消息时,消息以相反的顺序显示,但是在刷新数据(重新输入聊天活动)时,所有消息都以正确的顺序显示。我的问题是如何解决此问题。