我在Firebase上创建了学校数据库,我想对一所学校的所有相同键进行求和。像School1拥有Subject key一样,里面的Subject拥有学生:name1,name2等,每个学生都有相同的学科“ AAA”,“ BBB”,“ CCC”,现在我想对学科“ AAA”求和,您能帮我吗怎么才能将“ AAA”键值相加
{
"School1": {
"Subject": {
"Name1": {
"AAA": 50,
"BBB": 60,
"CCC": 70,
"DDD": 80
},
"Name2": {
"AAA": 50,
"BBB": 60,
"CCC": 70,
"DDD": 80
},
"Name3": {
"AAA": 50,
"BBB": 60,
"CCC": 70,
"DDD": 80
}
}
},
"School2": {
"Subject": {
"Name1": {
"AAA": 50,
"BBB": 60,
"CCC": 70,
"DDD": 80
}
}
}
}
AAA的输出结果:
学校1: AAA:150
答案 0 :(得分:1)
这是解决方法。
DatabaseReference aaa = FirebaseDatabase.getInstance()。getReference()。child(“ School1”)。child(“ Subject”);
aaa.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
int sum = 0;
for (DataSnapshot child : dataSnapshot.getChildren()) {
sum = (int) child.child("AAA").getValue() + sum;
}
Toast.makeText(MainActivity.this, "Total Sum is "+ sum, Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});