Skip to content Skip to sidebar Skip to footer

Firebase Database Retrieving Sum Of Multiple Childs

I want to do sum of multiple child nodes in Firebase real-time database Here is my database, in this I want to do sum of 'amount' child, so how to do that? Please Help!

Solution 1:

As I see in your database, your amount property is of type String and not number. So you cannot simply create a sum of String literals. To solve this you need to change your property name to be of type number. I also see that you are storing the currency along with the number. You should add the currency programmatically user side and not in the database. If you consider to change the type of your amount property, then please see my answer from this post

However, if you want to keep your actual database structure, you can sum all amounts using the following trick:

ValueEventListener eventListener = newValueEventListener() {
    @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
        int total = 0;
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String amount = ds.child("amount").getValue(String.class);
            int value = Integer.valueOf(amount.replace(" Rs.", ""));
            total =+ value;
        }
        Log.d("TAG", String.valueOf(total) + " Rs.");
    }

    @OverridepublicvoidonCancelled(DatabaseError databaseError) {}
};
your_database_reference.addListenerForSingleValueEvent(eventListener);

The output in your logcat will be:

27000

Solution 2:

You can use firebase's addValueEventListener method for this and loop dataSnapshot to calculate total of each amount child

your_database_reference.addValueEventListener(newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
    int totalamount = 0;
    for (DataSnapshotsnapshot: dataSnapshot.getChildren()) {
        // TODO: handle the dataSnapshotString amount = snapshot.child("amount").getValue();
        // remove _Rs. from amount and typecase it to int
        totalAmount += amount;
    }
}

@OverridepublicvoidonCancelled(DatabaseError databaseError) {
    // Getting Post failed, log a messageLog.w(TAG, "loadPost:onCancelled", databaseError.toException());
    // ...
}
});

Post a Comment for "Firebase Database Retrieving Sum Of Multiple Childs"