Firebase数据库检索多个子项的总和 [英] Firebase Database retrieving sum of multiple childs

查看:50
本文介绍了Firebase数据库检索多个子项的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对Firebase实时数据库中的多个子节点求和

I want to do sum of multiple child nodes in Firebase real-time database

这是我的数据库,在此我要对金额" 子项求和,那么该怎么做?

Here is my database, in this I want to do sum of "amount" child, so how to do that?

请帮助!

推荐答案

正如我在您的数据库中看到的那样,您的amount属性的类型为String而不是number.因此,您不能简单地创建String文字的总和.要解决此问题,您需要将属性名称更改为number类型.我还看到您正在将货币与数字一起存储.您应该以编程方式在用户端而不是在数据库中添加货币.如果您考虑更改amount属性的类型,请从此

As I see in your database, your amount property is of type String and not number. So you cannot simply create a sum of String literals. To solve this you need to change your property name to be of type number. I also see that you are storing the currency along with the number. You should add the currency programmatically user side and not in the database. If you consider to change the type of your amount property, then please see my answer from this post

但是,如果要保留实际的数据库结构,则可以使用以下技巧对所有金额求和:

However, if you want to keep your actual database structure, you can sum all amounts using the following trick:

ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int total = 0;
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String amount = ds.child("amount").getValue(String.class);
            int value = Integer.valueOf(amount.replace(" Rs.", ""));
            total =+ value;
        }
        Log.d("TAG", String.valueOf(total) + " Rs.");
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
your_database_reference.addListenerForSingleValueEvent(eventListener);

您的logcat中的输出将是:

The output in your logcat will be:

27000

这篇关于Firebase数据库检索多个子项的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆