Summing up with a child's value from firebase?

1

Hello , I would like to get a child value in firebase , add number and update child strong> with the result of the sum.

Code in OnCreate ()

uDataBase = FirebaseDatabase.getInstance().getReference().child("Bilhetes").child("total");


    uDataBase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            int total = dataSnapshot.getValue(int.class);

            textoT = total;




        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Code publishing in database

result = (textoT + 10);

        uDataBase.setValue(result);

Thank you in advance.

    
asked by anonymous 14.04.2017 / 05:08

1 answer

1

If I understand what you're wanting to do, it would just read the "total" child, add 10 in value and write it back into the same child, right?

There are a few ways to do this, even simpler forms, but if it's for just a simple increment in onCreate, I suggest the following changes:

  • Remove the child ("total") from the referrer;
  • If you leave the addValueEventListener, it will be monitoring subsequent changes and consequently leave an active viewer, which seems uninteresting in this case.
  • Read the object in child ("total") and convert to integer (make sure the contents of this field is an integer.
  • Add 10
  • Recording to the same child.

Practical example:

uDataBase = FirebaseDatabase.getInstance().getReference().child("Bilhetes");
uDataBase.addListenerForSingleValueEventr(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int total = (int) dataSnapshot.child("total").getValue(); // Carrega o valor do child "total" na variavel inteira total
        total = total + 10;                                       // Incrementa 10 na variavel total (exemplo)
        uDataBase.child("total").setValue(total);                 // Grava a variável total já incremenmtada no child "total"
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
    }
});

I did not test, but see if it works.

    
08.06.2017 / 02:36