1

I've recently begun using the FirebaseDatabase library on Android Studio. So, I've read that when you update/modify multiple locations on your Firebase Database, in case any error occurs and to make sure that data isn't modified in some locations and not modified in other, transactions are used.

Transactions in JavaScript have been covered thoroughly and proper documentation has been provided. But, the documentation for the Android Studio library isn't very clear. The links are link1 and link2


What is Mutable data and what value does it hold? Right now, this is how I update or modify the data on my database. I need to update values at nodes posts and user

HashMap<String, Object> hm = new HashMap<>();
hm.put("/users/"+key+"/name/","New Name");
hm.put("/posts/"+key+"/number_of_posts/", 2);
FirebaseDatabase.getInstance().getReference().updateChildren(hm, new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
        if(databaseError == null)
            Log.d(TAG, "TASK WAS SUCCESSFULLY COMPLETED");
        else
            Log.d(TAG, "SOMETHING WENT WRONG");
    }
});

I know this is the wrong way to do this, so an explanation or a link to a tutorial to do this would be really helpful.

Priyantha
  • 4,839
  • 6
  • 26
  • 46
  • 1
    The Firebase documentation has a pretty decent example of transactions here: https://firebase.google.com/docs/database/android/read-and-write#save_data_as_transactions. But transactions and multi-path updates are inherently different, since [transactions only work on a single location](http://stackoverflow.com/questions/39297884/how-can-i-use-a-transaction-while-performing-a-multi-location-update-in-firebase). – Frank van Puffelen Feb 16 '17 at 00:54
  • So is there any other secure way that I can carry out multi-path updates? Or is my current method the right way to do it? – Ashwin Gopi Krishna Feb 17 '17 at 11:40

2 Answers2

4

So apparently this was the right way after all. Whenever you need to perform multi-path updates, you use a Hash-Map and the function updateChildren(hashMap). A completion listener is optional and can be added. https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html

1

It is now possible to combine multi-path updates with transactions with the introduction of ServerValue.increment()

HashMap<String, Object> hm = new HashMap<>();
hm.put("/users/"+key+"/name/","New Name");
hm.put("/posts/"+key+"/number_of_posts/", ServerValue.increment(2));
FirebaseDatabase.getInstance().getReference().updateChildren(hm);

Link to release notes

drishit96
  • 327
  • 1
  • 2
  • 18