Skip to content Skip to sidebar Skip to footer

Update Multiple Fields In Multiple Nodes Simultaneously In Firebase (android)

I am trying to update multiple fields in different nodes using Maps and Update children however firebase is deleting the data in the respective nodes and adding the data. I want th

Solution 1:

The following solution is working based on @Alex Mamos suggestion is working...

Map<String, Object> map = new HashMap<>();
map.put("/users/" + currentUserId + "/name/", "Albert Einstein");
map.put("/users/" + currentUserId + "/score/", 23);
map.put("/user_detail_profile/" + currentUserId + "/claps/", 45);
map.put("/user_detail_profile/" + currentUserId + "/comments/", 8);
fbDbRefRoot.updateChildren(map);

Somehow inserting maps inside maps does not work. It all has to be a part of a large map.

Solution 2:

I am trying to update multiple fields in different nodes using Maps and Update children however firebase is deleting the data in the respective nodes and adding the data.

This is happening when you are using DatabaseReference's setValue(Object value):

Set the data at this location to the given value.

Going forward,

I want the data to be updated and previous data to remain the same.

In this case, you should use DatabaseReference's updateChildren(Map update), I see you are already using it in your code.

Update the specific child keys to the specified values.

Going even further,

This is working but I would like to do it in one shot so a success listener can be attached on all or none basis.

In this case, you should use batch operations, as explained in my answer from the follwing post:

You can now add a complete listener or a success listener to the batch operation. Please also note, that is an atomic operation, which means that either all of the operations succeed, or none of them are applied.

Solution 3:

Hey there you can use push method while adding data to firebase node

Here is how you create instance

privatelateinitvar database: DatabaseReference
    // ...
    database = FirebaseDatabase.getInstance().reference

This is how you simply add data

    mDatabase.child("users").child(userId).child("username").setValue(name);

And this is how you push data

Stringkey = mDatabase.child("posts").push().getKey();
    Post post = new Post(userId, username, title, body);
    Map<String, Object> postValues = post.toMap();

    Map<String, Object> childUpdates = new HashMap<>();
    childUpdates.put("/posts/" + key, postValues);
    childUpdates.put("/user-posts/" + userId + "/" + key, postValues);

    mDatabase.updateChildren(childUpdates);

Also if you want to update specific filed

Here is a Link

https://firebase.google.com/docs/database/android/read-and-write#update_specific_fields

Post a Comment for "Update Multiple Fields In Multiple Nodes Simultaneously In Firebase (android)"