Reputation: 759
I want to update the last message, try multiple methods but little bit confused what is the exact code to update the last message. Thanks in advance. Below is the code that I have tried:
databaseReference = FirebaseDatabase.getInstance().reference.child("user").child(apiKey)
databaseReference.orderByChild("api_key").equalTo(loginModel.api_key).addValueEventListener(object : ValueEventListener{
override fun onCancelled(error: DatabaseError) {
}
override fun onDataChange(snapshot: DataSnapshot) {
if(snapshot.exists()){
val map = mutableMapOf<String, String>()
map["last_message"] = message
map["last_message_key"] = apiKey
//databaseReference.child("api_key").child(loginModel.api_key).updateChildren(map.toMap())
//databaseReference.updateChildren(map.toMap())
databaseReference.child(snapshot.key!!).setValue(chatUser)
Utils.showToast(requireContext(), "Exists")
}else{
Utils.showToast(requireContext(), "Not Exists")
userReference.setValue(chatUser)
}
}
})
Upvotes: 0
Views: 1278
Reputation: 421
Instead of use set()
method i think you should use update()
method. In that method you pass the object and firebase detect the properties that has been updated. I'm using it for my project and works fine.
Upvotes: -1
Reputation: 139029
To be able to update properties in Firebase Realtime Database when using a Query, then you should call getRef() directly on the DataSnapshot object, as explained in the following lines of code:
val rootRef = FirebaseDatabase.getInstance().reference
val apiKeyRef = rootRef.child("user").child("apiKey")
val query = apiKeyRef.orderByChild("api_key").equalTo(loginModel.api_key)
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.exists()) {
for (ds in dataSnapshot.children) {
val map = mutableMapOf<String, String>()
map["last_message"] = message
map["last_message_key"] = apiKey
ds.getRef().updateChildren(map)
}
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d("TAG", databaseError.getMessage()) //Don't ignore potential errors!
}
}
query.addListenerForSingleValueEvent(valueEventListener)
I also encourage you to attach a complete listener to all update operations, to always know if something goes wrong.
Upvotes: 1
Reputation: 491
It would be useful if you posted the code and also explained the outcome of your code for us to understand better.
Example from the docs: mDatabase.child("users").child(userId).child("username").setValue(name);
You can call .child
all the way to your preferred child and do a setValue()
.
From your code, the issue might be with the snapshot.key!!
value which seems to be pointing back to your apiKey
value.
What you need is mDatabase.child("user").child("2c3e...").child("-MXH..").updateChildren()
. setValue()
will overwrite everything in that node. You should debug to see what values you are seeing in each step.
Upvotes: 1