Reputation: 316
I am trying to create a chat app and I am trying to check if the user has seen a message or not. The app works fine for the user who has sent the message first but for the user who has sent the message after the first user, it keeps updating.
Here is the database structure
So, The value seen
keeps updating between true and false
for MFRVfDa3JrFi8Gg9aL2
which was sent by the second user.
Here is the Code
ValueEventListener seenListener;
private void seenMessage(String qid) {
db = FirebaseDatabase.getInstance().getReference().child("Message");
seenListener = db.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
for (DataSnapshot childdshot : dataSnapshot.getChildren()) {
Chats chat = childdshot.getValue(Chats.class);
if (chat.getReceiverID().equals(userId) && chat.getSenderId().equals(qid)) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("seen", true);
childdshot.getRef().updateChildren(hashMap);
}
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
So, What should I do to stop it from updating itself again and again?
Upvotes: 0
Views: 159
Reputation: 598728
Your addValueEventListener
gets triggered immediately with the current value, and then every time something changes. Since you change the value in onDataChange
, that triggers the listener again, and again, and...
To only read the value once and update it you'll want to use addListenerForSingleValueEvent
instead addValueEventListener
.
Upvotes: 3