PeterEssyen
PeterEssyen

Reputation: 15

How do i sum up values with the same key in firebase database

I'm creating a shopping app where users add items to cart and then I store these values in the Firebase database. The problem I've is trying to get the total amount of product added to the cart. I have a MapChild with key productPrice, now how do I sum up all the data with key productPrice after saving them in a listmap.

Here's a screenshot of my firebase database

Upvotes: 0

Views: 549

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

To sum all the values of the productPrice property, please use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference cartItemsRef = rootRef.child("cartItems");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        long total = 0;
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String productPrice = ds.child("productPrice").getValue(String.class);
            total += Long.parseLong(productPrice);
        }
        Log.d("TAG", "total: " + total);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
    }
};
cartItemsRef.addListenerForSingleValueEvent(valueEventListener);

The result in the logcat will be:

total: 730

If you need to store prices, it's best to store them as numbers and not as String values, as you do right now. If you intend to change that, then you should simply use:

total += productPrice;

Upvotes: 2

Related Questions