如何使用Firebase数据库收集子项内的数值

时间:2018-04-17 07:20:09

标签: android firebase firebase-realtime-database

您好我正在尝试开发一个应用程序。我可以告诉你我是新手。我想使用Firebase数据库汇总标题下的子项的数值。我怎样才能做到这一点?

示例Children1 =" 10"儿童2 =" 20"我想要Children1 + Children2 = 30

2 个答案:

答案 0 :(得分:2)

你可以试试这个

private FirebaseDatabase database = FirebaseDatabase.getInstance();
private final DatabaseReference myRef = database.getReference("IndexOfYourDatabase"); //Init your ref according to your index
private int res = 0;

myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
             for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {                       
                  res += Integer.parseInt(messageSnapshot.child("").getValue().toString()); //acces to the value of every child and count them in res.
              }
         }

         @Override
         public void onCancelled(DatabaseError databaseError) {}
};

不要忘记用gour Index

替换IndexOfYourDatabase

通过这种方式,您可以实现for循环以添加孩子的值

答案 1 :(得分:0)

如果您想计算来自不同孩子的单个值,请使用以下代码: -

 FirebaseDatabase.getInstance().getReference().child("database root name").child("database root field key").addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                   int val1 = Integer.parseInt(dataSnapshot.child("childern1").getValue().toString();
                   int val2 = Integer.parseInt(dataSnapshot.child("childern2").getValue().toString();

                   int total = val1 +val2;

                            }

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

如果您想计算记录数,

private int totalval= 0; 

FirebaseDatabase.getInstance().getReference().child("database root name").child(database root key name).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

             for (DataSnapshot innerChild : dataSnapshot.child("childern1").getChildren()) {

                            totalVal + = Integer.parseInt(innerChild.child("").getValue().toString();
                          }


                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });