How to get the sum of child nodes in Firebase database?

Please Share On:

Today, in this tutorial you will learn how to get the sum of child nodes in Firebase database.

In the below diagram, we get the total of recycling_items of particular user using their user id.

The below diagram is a Realtime Firebase database.

Here is the coding part, you get a sum of recycling_items.

//sum up all recycling_items
    private void sum_totalrecycledItems() {
        currentUser = mAuth.getCurrentUser();
        if (currentUser != null) {
            String uid = currentUser.getUid(); //Do what you need to do with the UserId

            //get the firebase database location for recycling items
            FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
            DatabaseReference databaseReference = firebaseDatabase.getReference().child("request_recycling").child(uid);

            databaseReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    int totalsum = 0;
                    for(DataSnapshot ds : dataSnapshot.getChildren()) {
                        if (dataSnapshot.exists() && dataSnapshot.getValue() != null){
                            //count value found
                            String count = Objects.requireNonNull(ds.child("recycling_items").getValue(String.class));
                            int value = Integer.parseInt(count);
                            totalsum = totalsum + value;
                        }
                        Log.d("TAG", "Count Value Found:" + totalsum);

                        //get the firebase database location for recycling items
                        FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
                        DatabaseReference databaseReference = firebaseDatabase.getReference().child("count").child(uid).child("total_recycled_count");

                        //set value to firebase database at total_recycled_count
                        databaseReference.setValue(totalsum);
                        Log.d("total_recycled_count:", String.valueOf(totalsum));
                    }

                }

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

                }
            });
        }
    }

Output:

Result display at logcat in android studio.



You may interest on the following topics:

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright @2023. All Right Reserved.


Social media & sharing icons powered by UltimatelySocial