Jenova Projects
Jenova Projects

Reputation: 119

How to get SUM of child entries in Firebase Database

I am trying to get the SUM of all int's in a child of my Firebase Database.

My Database is set up like

beans-card
   - users
        - (UID from Firebase Auth)
             - Receipt
                   - keyID
                       - amount: 11
                       - points: 22
                   - keyID
                       - amount: 11
                       - points: 22

I want to get the SUM of points and show in Textview in different Fragment

here is my Receipt Class

public class Receipt {

    public int amount;
    public int points;

    public Receipt(){}

    public Receipt(int amount, int points) {
        this.amount = amount;
        this.points = points;
    }

    public int getAmount(){
        return amount;
    }

    public void setAmount(int amount){
        this.amount = amount;
    }

    public int getPoints(){
        return points;
    }

    public void setPoints(int points){
        this.points = points;
    }

}

and here is how i'm entering the data into my database

Receipt receipt = new Receipt(second, second*2);

mDatabase.child("users").child(mUserId)
.child("Receipt").push().setValue(receipt);

Upvotes: 1

Views: 2711

Answers (1)

Ekrem
Ekrem

Reputation: 405

 DatabaseReference db_receipt =FirebaseDatabase.getInstance().getReference().child("users").child(uid).child("Receipt")
long sum = 0;
db_receipt.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds:dataSnapshot.getChildren()
                    ) {
                        sum = sum + points;
                        }

                }
            }


        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Upvotes: 3

Related Questions