I have this Snapshot listener that checks when a chat model is added or modified I want it to give it to me, but the snapshot listener works only when the activity starts and from there, it stops working. The problem is that it doesn’t even goes to the onEvent()…
this is the function where I initialize the snapshot listener.
the function triggered in the onCreate function.
private void addChatRoomSnapshotListener() {
chatRoomsListener = chatsQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
if (error != null) {
error.printStackTrace();
return;
}
for (DocumentChange change : value.getDocumentChanges()) {
switch (change.getType()) {
case ADDED:
ChatModel chatModel = change.getDocument().toObject(ChatModel.class);
chatModel.setId(change.getDocument().getId());
chats.add(chatModel);
adapter.notifyDataSetChanged();
break;
case MODIFIED:
Toast.makeText(getApplicationContext(), "modifeid", Toast.LENGTH_SHORT).show();
// Handle modified document
ChatModel modifiedChat = change.getDocument().toObject(ChatModel.class);
modifiedChat.setId(change.getDocument().getId());
// Find the position of the modified chat in the list
int modifiedIndex = findChatIndexById(modifiedChat.getId());
if (modifiedIndex != -1) {
// Replace the existing chat with the modified chat
chats.remove(modifiedChat);
chats.add(0, modifiedChat);
adapter.notifyDataSetChanged();
break;
}
}
}
}
});
}
here is how I remove the snapshot listener.
@Override
protected void onPause() {
super.onPause();
// Remove the snapshot listener to avoid memory leaks
Toast.makeText(getApplicationContext(), "listener removed", Toast.LENGTH_SHORT).show();
if (chatRoomsListener != null) {
chatRoomsListener.remove();
}
}
2
Answers
better you use childEventListner() insted of valueaddedlistner() .try once
I think it is because you are removing the listener onPause and not registering it again. Because onCreate is called once but onPause is can be called several times. Try this: Either remove the listener onDestroy or register the listener onResume.