Add it up to a firebase Child?

Asked

Viewed 915 times

2

Hello, Would like to get the value of a Child at firebase, add a number and update Child with the result of summing up.

Code on the 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 published in the database

result = (textoT + 10);

        uDataBase.setValue(result);

Thanks in advance.

1 answer

2


If I understood what you wanted to do, it would just read the "total" Child, add 10 in value and write it again on the same Child, right ?

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

  • Remove Child("total") from the referencer;
  • Replace addValueEventListener with addListenerForSingleValueEvent (as you will need only one access to this Child. If you leave the addValueEventListener, it will be monitoring later changes and consequently leave an active observer, which seems to me not interesting in this case.
  • Read the object in Child("total") and convert to integer (make sure the content of this field is an integer number.
  • Add 10
  • Re-record 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 didn’t test it, but see if it works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.