0

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) {

    }
});

1 Answers1

0

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);
    }
});
DHAVAL A.
  • 2,251
  • 2
  • 12
  • 27
  • Operator '+' cannot be applied to 'java.lang.Object', 'int' on currentMoney + moneyToAdd –  Mar 12 '20 at 04:02
  • i'm define this int moneyToAdd = 100; –  Mar 12 '20 at 04:02
  • Hello, I managed to implement without errors but something that was working now is giving an error on this line long v = Long.parseLong ((String) dataSnapshot.getValue ()); this line of code is from the previous activity when opening cassinopayment generates this error java.lang.NumberFormatException: Invalid long: "null" would you know how to fix it? could help me I believe that the solution you gave really works but this error appeared now and I don't know how to fix it –  Mar 12 '20 at 04:25
  • how can I pass a null value for this line long v = Long.parseLong ((String) dataSnapshot.getValue ()); sorry I'm new –  Mar 12 '20 at 04:34
  • Replace below line `long v = Long.parseLong ((String) dataSnapshot.getValue ());` with `long v = 0; if(dataSnapshot.getValue() != null){ v = Long.parseLong ((String) dataSnapshot.getValue ());}` – DHAVAL A. Mar 12 '20 at 04:36
  • I set private int moneyToAdd = 9; but node money has not been updated am i doing something wrong? –  Mar 12 '20 at 04:42
  • debug marker ref.runTransaction(new Transaction.Handler() results DataSnapshot { key = VsJZ6QEEzgMmD1nUxcYylaZZX0r1, value = {fullname=test test2, address=instagram, helpsms=sms, phone=55555555555, email=test@a.com, money=350, cassinotime=5, cassinoprofit=250, cassino={cassinotime=10000, cassinoprofit=250}} } –  Mar 12 '20 at 04:51
  • hoo thanks man one problem I had 10 in node money as I set int moneyToAdd = 100; when updated it generated a value of 910 in the node "money" how to fix this? –  Mar 12 '20 at 06:44
  • There is nothing wrong with code. Recheck your logic implementation once. – DHAVAL A. Mar 12 '20 at 07:01