Firebase runTransaction not working - MutableData is null
Solution 1:
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.
- When you first call
runTransaction()
the Firebase client will immediately invoke yourdoTransaction()
callback with its current guess for the current data. Quite often this will benull
. - Your code returns the next value based on the current value. In the case above, if the current value was
null
the new value will be1
. - The Firebase client then sends both the assumed current value and the new value to the server.
- If the actual stored value is the same as the assumed current value, the Firebase server writes the new value you specified.
- If the actual stored values is different from the assumed current value, the Firebase server rejects the new value and sends the actual current value to the client.
- At this stage the client goes back to step 1, with the now updated assumed current value.
If this does not explain the behavior you're seeing, you might want to check what values are passed into onComplete()
.