'How to set an additional value to an existing child to Firebase Realtime android kotlin
I need to set value to an existing child. For example:
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:
How can I add a "name" value so that others are not deleted?
Solution 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frank van Puffelen |
| Solution 2 | RiseHit |


