如何在Firebase数据库中获取子条目的SUM

时间:2017-05-27 22:32:10

标签: java android firebase firebase-realtime-database

我正在尝试在Firebase数据库的子项中获取所有int的SUM。

我的数据库设置如

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

我希望得到点的总和并在Textview中以不同的片段显示

这是我的收据类

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;
    }

}

以下是我如何将数据输入我的数据库

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

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

1 个答案:

答案 0 :(得分:2)

 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) {

        }
    });