Skip to content Skip to sidebar Skip to footer

Calculate Total From Values Stored In Firebase-android

I'm trying to create a total from numbers stored by the user on a cloud Firestore database. There will be a varying amount of values, depending on how many items the user adds to t

Solution 1:

To get the total that you are talking about, please use the following code:

userMenuRef.get().addOnCompleteListener(newOnCompleteListener<QuerySnapshot>() {
    @OverridepublicvoidonComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            double total = 0;
            for (QueryDocumentSnapshotdocument : task.getResult()) {
                double itemCost = document.getDouble("itemCost");
                total += itemCost;
            }
            Log.d("TAG", String.valueOf(total));
        }
    }
});

The output will be the sum of all itemCost property that exist in your documents.

Another approach would be to keep a running total over time, as each new price is known. Then, you can query for that running total in another document when you need it.

Post a Comment for "Calculate Total From Values Stored In Firebase-android"