Home > Mobile >  How to set an additional value to an existing child to Firebase Realtime android kotlin
How to set an additional value to an existing child to Firebase Realtime android kotlin

Time:03-08

I need to set value to an existing child. For example:

enter image description here

I have Users -> profileUid -> phone and uid, but i want to add new value, for example - name, that i have three values: phone, profileUid and name.

I used this code to add "name":

private fun setName(name: String) {
    val hashMap = HashMap<String, Any>()
    hashMap["name"] = name

    val reference = FirebaseDatabase.getInstance().getReference("Users")

    reference.child(getProfileUid()!!)
        .setValue(hashMap)
        .addOnSuccessListener {
            Toast.makeText(requireContext(), "Успешно!", Toast.LENGTH_SHORT).show()
        }
        .addOnFailureListener {
            Toast.makeText(requireContext(), "Ошибка!", Toast.LENGTH_SHORT).show()
        }
}

But if I do it this way, then all the values ​​are removed and only the name remains, like on this screenshot:

enter image description here

How can I add a "name" value so that others are not deleted?

CodePudding user response:

If you want to update only write the child nodes you have in your map, use updateChildren:

reference.child(getProfileUid()!!)
    .updateChildren(hashMap)

Also see the Firebase documentation on updating specific fields.

CodePudding user response:

you can try use SetOptions.merge(), this would look like

reference.child(getProfileUid()!!)
    .setValue(hashMap, SetOptions.merge()).addOnSuccessListener {
        Toast.makeText(requireContext(), "Успешно!", Toast.LENGTH_SHORT).show()
    }
    .addOnFailureListener {
        Toast.makeText(requireContext(), "Ошибка!", Toast.LENGTH_SHORT).show()
    }

merge takes care of updating the document without replacing existing data, but if you're not sure the document exists, don't use the option to merge the new data with any existing document, to avoid overwriting entire documents.

  • Related