我在任何私有方法之外使用EventListener,以便以后可以在onStart()
方法中调用它:
此侦听器的目的是,聊天应用程序将显示消息的接收者是否已查看该消息。我想我可能做错了。
ListenerRegistration
的声明发生在onCreate()方法之前
ListenerRegistration listenerRegistration;
EventListener(在onCreate()方法内部)
EventListener<DocumentSnapshot> eventListener = new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable FirebaseFirestoreException e) {
if (snapshot != null){
String recipientId = getIntent().getStringExtra("recipientId");
Chat chat = snapshot.toObject(Chat.class);
if (chat.getReceiver().equals(userId) && chat.getSender().equals(recipientId)){
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("isseen", true);
FirebaseFirestore.getInstance().collection("chats").document(roomId).collection("messages").add(hashMap);
}
}
}
};
onStart()方法
@Override
protected void onStart() {
super.onStart();
listenerRegistration = FirebaseFirestore.getInstance().collection("chats").document(roomId).collection("messages").addSnapshotListener(MessageActivity.this,eventListener);
}
[请看一下EventListener,让我知道是否应该将其更改为QuerySnapshot或QueryDocumentSnapshot,因为我正在使用DocumentSnapshot,并且它们警告我事件侦听器中的getReceiver方法将创建NullPointerException。
(还有一些可能会或可能不会有用的额外信息:-每条消息都存储在“消息”集合内的随机生成的文档中]
getReceiver()
的错误消息与所接收的快照类型无关。实际上,实际上您没有选择快照类型-您必须使用API为您提供的快照类型来进行查询。