[英]How to change the value of child of an unknown parent in Firebase - Android
I'm working on a Firebase chat app. 我正在使用Firebase聊天应用。 I have been trying to change child value for an unknown parent in Firebase but I can't get it right.
我一直试图在Firebase中更改未知父级的子值,但我无法正确使用它。
Here is my Firebase database structure: 这是我的Firebase数据库结构:
I want to change the value of "seen" from false
to true
when the user opens Messages activity. 我想在用户打开Messages活动时将“seen”的值从
false
更改为true
。
Each message has a push id which I don't know the value. 每条消息都有一个推送ID,我不知道该值。 I want to be able to edit a child of push id.
我希望能够编辑推送ID的子项。
Here is my code: 这是我的代码:
DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);
messageRef.child("seen").setValue(true).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("isseen", "Seen set to true");
} else {
Log.d("isseen", "Seen not set to true");
}
}
});
How best can I achieve my desired results? 我如何才能达到理想的效果?
To solve this, you need to use a query. 要解决此问题,您需要使用查询。 So please use the following lines of code:
所以请使用以下代码行:
DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);
Query query = messageRef.orderByChild("seen").equalTo(false);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ds.child("seen").getRef().setValue(true);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
The result will the change of your seen
property from false
to true
. 结果将您
seen
属性从false
更改为true
。
If you also consider at some point to try using Cloud Firestore , here you can find a tutorial on how to create a complete and functional Firestore Chat App using Kotlin . 如果您还考虑尝试使用Cloud Firestore ,可以在此处找到有关如何使用Kotlin创建完整且功能齐全的Firestore Chat应用程序的教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.