I am trying to use runTransaction()
of Firebase database but it is not working. Here is the code I am using.
numQuestionRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
String numQuestions = (String) mutableData.getValue();
long value = Long.parseLong(numQuestions, 16);
value++;
String incHex = Long.toHexString(value);
mutableData.setValue(incHex);
return Transaction.success(mutableData);
}
@Override
public void onComplete(FirebaseError firebaseError, boolean b, DataSnapshot dataSnapshot) {
}
});
This code is activated when I press a button within my app. When I press the button for the first time since launching the app, my database does not change. But when I press the button the second time since launching the app, it updates it to the next number. I don't understand what it wrong or why it only does it on the second button press.
You'll want to follow the pattern used in the Firebase documentation for handling transactions and handle the case where there's no current value your transaction callback:
public Transaction.Result doTransaction(MutableData currentData) {
long value = 0;
if(currentData.getValue() != null) {
String numQuestions = (String) currentData.getValue();
value = Long.parseLong(numQuestions, 16);
}
value++;
String incHex = Long.toHexString(value);
currentData.setValue(incHex);
return Transaction.success(currentData);
}
The reason you need to do this is that Firebase may (and often will) execute your transaction callback multiple times and you need to cater for that.
runTransaction()
the Firebase client will immediately invoke your doTransaction()
callback with its current guess for the current data. Quite often this will be null
.null
the new value will be 1
.If this does not explain the behavior you're seeing, you might want to check what values are passed into onComplete()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With