Oscar Ruiz
Oscar Ruiz

Reputation: 3

How to get a sum of all values from a node in Firebase?

this is my Database structure:

JSON

I want to get the sum from all child values, from example for I want to get de value "5" that is the sum from all de values of the Node "UNICARIBE"

Upvotes: 0

Views: 1405

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

To count all those value, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference unicaribeRef = rootRef.child("Unicaribe");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int total = 0;
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            int value = ds.getValue(Integer.class);
            total =+ value;
        }
        Log.d("TAG", String.valueOf(total));
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
unicaribeRef.addListenerForSingleValueEvent(eventListener);

Your output will be 5.

Upvotes: 3

Related Questions