Q:

how to sum money value in firebase realtime android studio

how to sum money value in firebase realtime android studio
Hello how can I sum a value with the existing node value?
Every time onDataChange is called, sum the value with the value of the "money" node of the firebase
any help is welcome.
my code
FirebaseDatabase.getInstance().getReference("Users");
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
        ref.child("Users").child(userUid).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
            ref.child("Users").child(userUid).child("money").setValue("350");
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

A:

Instead of making simple write operation, you can use transaction.
Just refer below code.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference()
            .child("Users").child(userUid).child("money");

ref.runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData mutableData) {
        Object currentMoney = mutableData.getValue();
        int totalMoney = 0;
        if (currentMoney == null) {
             totalMoney = moneyToAdd;
        } else {
             totalMoney = Integer.parseInt(currentMoney) + moneyToAdd;
        }

        mutableData.setValue(totalMoney);
        return Transaction.success(mutableData);
    }

    @Override
    public void onComplete(DatabaseError databaseError, boolean b,
                           DataSnapshot dataSnapshot) {
        // Transaction completed
        Log.d(TAG, "postTransaction:onComplete:" + databaseError);
    }
});

