Reputation: 543
On Firebase database I have a key - "Coins" and its value - "20". Now I want to add 5 to the value (ie coins) directly on the server.
So every time the user clicks the button the value of Coins should increment by 5 directly on the server. Is there any way to do so?
Upvotes: 0
Views: 1746
Reputation: 599571
As Fattie commented, you'd use Firebase Database transactions for this. With a transaction, you get the client's best guess for the current value and return the new value based on that. So in your case:
coinsRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
long value = 0;
if (mutableData.exists()) {
value = mutableData.getValue(Long.class);
}
value = value + 5;
mutableData.setValue(value);
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
Log.d(TAG, "runTransaction:onComplete:" + databaseError);
}
});
Upvotes: 1