I am facing a problem of how to exactly use Firebase Transaction runTransaction()
method. Here when the user clicks the button I am trying to fetch the value from database and increment it and then again send it back to database. Now issue is what if multiple users tap the button at the same time, for this I am using Firebase transaction. But don't know exactly how to write the code. Here is the code which I have tried but not working. I just want to update the value from 0 to 1, if button is clicked by only one user and if clicked simultaneously by many users, then one of the user should wait until the first user completes the updating.
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(final DataSnapshot dataSnapshot) {
final String mainValue = (String) dataSnapshot.child("values").child("number").getValue();
btnInc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(final MutableData mutableData) {
mutableData.child("number").setValue(String.valueOf(Integer.parseInt(mainValue) + 1));
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
Toast.makeText(MainActivity.this, "Result: "+b, Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});