madhushri
madhushri

Reputation: 11

Firebase sum all child entries when child values match

i have saw this question in sql this question but how this will be implement in firebase. This is my firebase structure database

I need to sum up the expenses total as per name . I need output like this

output

petrol:25
oil:83
gross:25

I have tried below code

expensesaddref=databaseReference.child(username).child(monthyr);
totaldatabaseref=databaseReference.child(username).child("Expense Cost").child(monthyr);
expensesaddref.orderByChild("expensesName").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        Log.d("Tag", "on  exp total");
        int tot=0;
        String exp = null;
        for(DataSnapshot ds:dataSnapshot.getChildren()){
            ExpenseClass expenseAdd=ds.getValue(ExpenseClass.class);
            tot+=expenseAdd.getTotal();
            exp=expenseAdd.getExpensesName();

        }
        ExpenseClass expensesAdd=new ExpenseClass(exp,tot);
        String ref= "expensescost_"+ expensesAdd.getExpensesName();
        totaldatabaseref.child(ref).setValue(expensesAdd);
        Log.d("TAG", exp + "");
        Log.d("TAG", tot + "");


        Log.d("Tag", "After exp total");

    }

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

    }
});

I got the output as 0. Please help me

Upvotes: 0

Views: 1216

Answers (1)

PradyumanDixit
PradyumanDixit

Reputation: 2375

You can use orderByChild() and then get the total child value to sum it. What I am saying looks something like this in code:

ref.child("October_2018").orderByChild("expensesName").equalTo("oil").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot data: dataSnapshot.getChildren()){
                  int sum=0;
                  sum += data.child("total").getValue(Integer.class);  


                }

            }

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

            }
        });

Here ref is DatabaseReference to your Firebase database.

Upvotes: 1

Related Questions