0

**I need help. I am facing some problems while developing an app. This is my first time working with int value.

Suppose a user has an ID in the Firebase database. In the Balance node under his mobile number, there are 2 int values "task" and "referral" like the picture. firebase database When someone will use his number as a reference I want to add int 20 with his old referral balance. I tried everything I could but after putting the new value into the database the balance value keeps increasing until the app crashes.**

saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           
            creditRef();
        }
    });
}

private void creditRef() {
    ref = ref_mob.getText().toString();
    balData.child(ref).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot)
        {
            if (dataSnapshot.exists())
            {
                String old = dataSnapshot.child("referral").getValue().toString();

                double num1 = Double.parseDouble(old);
                double num2 = Double.parseDouble(String.valueOf(20));

                double sum = num1 + num2;

                HashMap<String, Object> balMap = new HashMap<>();
                balMap.put("referral", sum);

                balData.child(ref).updateChildren(balMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task)
                    {
                        if (task.isSuccessful())
                        {
                            Toast.makeText(AddDetailsActivity.this, "Reference credited", Toast.LENGTH_SHORT).show();

                        }
                    }
                });

            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

1 Answers1

0

The most simple solution for an increment operation is:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference referralRef = rootRef.child("Balance").child("01555555125").child("referral");
referralRef.setValue(ServerValue.increment(20));

If you more than that, I recommend you use transactions, as explained in my answer from the following post:

How to save users score in firebase and retrieve it in real-time in Android studio

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193