简体   繁体   English

如何更新 Firebase 数据库中子项的特定值

[英]How to update particular value of child in Firebase Database

在此处输入图像描述

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)
                }
            }
        })

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);文档中的示例: mDatabase.child("users").child(userId).child("username").setValue(name); You can call .child all the way to your preferred child and do a setValue() .您可以一直调用.child到您喜欢的孩子并执行setValue() From your code, the issue might be with the snapshot.key!!从您的代码中,问题可能出在snapshot.key!! value which seems to be pointing back to your apiKey value.似乎指向您的apiKey值的值。 What you need is mDatabase.child("user").child("2c3e...").child("-MXH..").updateChildren() .您需要的是mDatabase.child("user").child("2c3e...").child("-MXH..").updateChildren() setValue() will overwrite everything in that node. setValue()将覆盖该节点中的所有内容。 You should debug to see what values you are seeing in each step.您应该调试以查看您在每个步骤中看到的值。

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:为了能够在使用查询时更新 Firebase 实时数据库中的属性,那么您应该直接在 DataSnapshot object 上调用getRef() ,如以下代码行中所述:

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.我还鼓励您为所有更新操作附加一个完整的侦听器,以始终知道是否出现问题。

Instead of use set() method i think you should use update() method.而不是使用set()方法,我认为你应该使用update()方法。 In that method you pass the object and firebase detect the properties that has been updated.在该方法中,您通过 object 和 firebase 检测已更新的属性。 I'm using it for my project and works fine.我将它用于我的项目并且工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM