英文:
Firebase database Doesn't stop updating value
问题
我正在尝试创建一个聊天应用程序,并尝试检查用户是否已经看过一条消息。对于首先发送消息的用户,该应用程序运行正常,但对于在第一个用户之后发送消息的用户,它不断更新。
这是数据库结构:
因此,值seen
在第二个用户发送的MFRVfDa3JrFi8Gg9aL2
消息中不断更新。
这是代码:
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) {
}
});
}
那么,我应该怎么做才能阻止它不断自我更新呢?
英文:
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?
答案1
得分: 3
你的 addValueEventListener
会立即触发当前值,并在每次发生更改时再次触发。因为你在 onDataChange
中更改了值,这会再次触发监听器,一次又一次地触发……
如果只想读取值一次并进行更新,你应该使用 addListenerForSingleValueEvent
,而不是 addValueEventListener
。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论