[英]Retrieve data from multiple push ids under a single child in firebase realtime database
I am new to android studio and programming and am currently trying to make my first app.我是 android 工作室和编程的新手,目前正在尝试制作我的第一个应用程序。 In firebase RTDB, I have multiple push ids under a single child that keep on increasing in number as the user presses certain buttons, and they all store only an integer. I want to retrieve the data from all those push ids(or keys, I don't really know what they are actually called) under the child and then sum the integers up and display the result in a
textView
and do it every time a new field is added.在 firebase RTDB 中,我在一个孩子下有多个推送 ID,随着用户按下某些按钮,它们的数量不断增加,它们都只存储一个 integer。我想从所有这些推送 ID(或键,我真的不知道它们实际上叫什么)在孩子下面,然后将整数相加并将结果显示在
textView
中,并在每次添加新字段时执行此操作。 How can I do that?我怎样才能做到这一点? So far I only know how to normally send and receive data to childs sub-childs like this but i have never ever used push ids or keys before:
到目前为止,我只知道如何像这样正常地向孩子的子孩子发送和接收数据,但我以前从未使用过推送 ID 或密钥:
String recieve = datasnapshot.child("Child").child("subchild").getText().toString();
String send = "send";
databaseReferenc.child("Child").child("sunchile").setValue(send);
The data tree in firebase is as follows: firebase中的数据树如下:
Assuming that Australia
is a direct child of your Firebase Realtime Database root, to sum all those values, please use the following lines of code:假设
Australia
是您的 Firebase 实时数据库根目录的直接子目录,要对所有这些值求和,请使用以下代码行:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference australiaRef = rootRef.child("Australia");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int total = 0;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String value = Integer.parseInt(ds.getValue(String.class));
total += value;
}
Log.d("TAG", "total: " + total);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
australiaRef.addListenerForSingleValueEvent(valueEventListener);
One more thing.还有一件事。 Because you are storing numbers, it best to store them as long values and not as String values.
因为要存储数字,所以最好将它们存储为长值而不是字符串值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.