I'm working on a Firebase chat app. I have been trying to change child value for an unknown parent in Firebase but I can't get it right.
Here is my Firebase database structure:
I want to change the value of "seen" from false
to true
when the user opens Messages activity.
Each message has a push id which I don't know the value. I want to be able to edit a child of push 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
.
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.