Search code examples
javaandroidfirebasefirebase-realtime-databasetransactions

Saving Transactional Data


Can we add a new child with the help of run transaction in an Android Firebase project?


Solution

  • Can we add a new child with the help of run transactions in an Android Firebase project?

    Sure we can. As the docs states, if the value that we are trying to increment using transactions doesn't exist at the location we are pointing to, we can simply set it:

    Integer currentValue = mutableData.getValue(Integer.class);
    if (currentValue == null) {
      mutableData.setValue(1);
    } else {
      mutableData.setValue(currentValue + 1);
    }
    

    Otherwise, we read the value and increment it.

    If you don't need to read the value and you just want to increment it, you can simply use:

    ref.child("propertyName").setValue(ServerValue.increment(1));