我如何在Firebase数据库中添加值并存储总数

时间:2019-11-05 16:57:26

标签: android firebase firebase-realtime-database

  reference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                   double total = 0;

                    for( DataSnapshot ds :dataSnapshot.getChildren()) {
                        incomeinfo incomeinfo = ds.getValue(incomeinfo.class);
                        double amount = Double.valueOf(incomeinfo.getAmount());
                        total = total + amount;
                    }
                }

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

                }
            });

这是我添加总金额的参考代码

public class incomeinfo {

    public String payeename;
    public double amount;
    public String status;
    public String mod;
    public double total;

    public String getPayeename() {
        return payeename;
    }

    public void setPayeename(String payeename) {
        this.payeename = payeename;
    }

    public double getAmount() {
        return amount;
    }

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

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMod() {
        return mod;
    }

    public void setMod(String mod) {
        this.mod = mod;
    }

    public double getTotal() {
        return total;
    }

    public void setTotal(double total) {
        this.total = total;
    }

    public incomeinfo(String payeename, double amount, String status, String mod, double total) {
        this.payeename = payeename;
        this.amount = amount;
        this.status = status;
        this.mod = mod;
        this.total = total;
    }
}

我的incomeinfo类,用于将数据存储到Firebase

firebase overview need to add the amount sum in all the different groups click here to view the image

有人请帮我加上所有金额的总和。

1 个答案:

答案 0 :(得分:0)

在for-each循环之后,您必须再次遍历数据库,并根据之前计算的值设置“总计”字段,并将每个IncomeInfo实例保存到DB中。
像这样

for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    incomeinfo incomeinfo = ds.getValue(incomeinfo.class);
                    incomeinfo.setTotal(total);
                    dbHelper.saveIncomeinfo(incomeinfo);
                }