我不确定如何监听Firestore数据库中的更改以及如何更新RecyclerView
中的项目。
我正在尝试使用Firestore数据库做一个聊天应用程序。现在,我想实现一个功能,发件人可以查看收件人是否已看到消息。最初,发件人的最后一封邮件附近有“已送达”状态。接收者打开聊天室后,状态应立即更改为“已看到”。
我正在观看YouTube上KOD Dev的教程“带有Firebase Part 14的聊天应用程序”,但使用Firestore db而非Realtime数据库。
聊天模型的一部分,带有RecyclerView
的活动和适配器。
public class Chat {
private String sender;
private String receiver;
private String message;
private boolean isseen;
public Date sent_timestamp;
public Chat(String sender, String receiver, String message, boolean isseen, Date sent_timestamp) {
this.sender = sender;
this.receiver = receiver;
this.message = message;
this.isseen = isseen;
this.sent_timestamp = sent_timestamp;
private void seenMessage(final String userid) {
Query query = mFirebaseFirestore.collection("Chats");
query.addSnapshotListener(this, new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
QueryDocumentSnapshot docEvent = doc.getDocument();
Chat chat = doc.getDocument().toObject(Chat.class);
if (chat.getReceiver().equals(fuser.getUid()) && chat.getSender().equals(userid)) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("isseen", true);
doc.getDocument().getReference().update(hashMap);
}
}
}
}
});
private void readMessages(final String myid, final String userid, final String imageurl) {
mchat = new ArrayList<>();
messageAdapter = new MessageAdapter(MessageActivity.this, mchat, imageurl);
recyclerView.setAdapter(messageAdapter);
Query query = mFirebaseFirestore.collection("Chats").orderBy("sent_timestamp", Query.Direction.ASCENDING);
query.addSnapshotListener(this, new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
QueryDocumentSnapshot docEvent = doc.getDocument();
Chat chat = doc.getDocument().toObject(Chat.class);
if (chat.getReceiver().equals(myid) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(myid)) {
mchat.add(chat);
}
}
messageAdapter.notifyDataSetChanged();
}
}
});
}
@Override
public void onBindViewHolder(@NonNull MessageAdapter.ViewHolder holder, int position) {
Chat chat = mChat.get(position);
if (position == mChat.size() - 1) {
if (chat.isIsseen()) {
holder.txt_seen.setText("Seen");
} else {
holder.txt_seen.setText("Delivered");
}
} else {
holder.txt_seen.setVisibility(View.GONE);
}
值“ isseen”更改为“ true”后,它应立即显示在发送者的电话上。
最佳答案
尝试以下查询
Query query = mFirebaseFirestore.collection("Chats").whereEqualTo("isseen", true);
它将在isseen = true以及任何“ isseen”实时更改为true时提供所有消息的列表。