I am making an android app using android studio. I have linked it to firebase Realtime database. I want to retrieve the sum of some child values in one of the activities. This is my json file:-
{
"Data" : {
"UyhzVqsz1BVFKoePa2NEmlPFu382" : {
"Budget" : {
"Expanse" : {
"Wedding" : {
"stData1" : "W",
"stData2" : "Wedding",
"stData3" : "111",
"stData4" : "11111"
}
}
},
"Traffic" : {
"Wedding" : {
"-MYKeSN8GZ8WbI-8TfVB" : {
"stData1" : "15 Apr 2021,06:43:00:pm",
"stData2" : "Wedding",
"stData3" : "kkk",
"stData4" : "100"
},
"-MYLu2qPmt9qj1tJPkrP" : {
"stData1" : "16 Apr 2021,00:30:47:am",
"stData2" : "Wedding",
"stData3" : "ddd",
"stData4" : "200"
}
}
}
}
}
}
I have seen many possible solutions to this problem .I applied many of them in my app .But none of the worked. The following code worded a bit. Now the problem is that this code brings the value of the last entered data. I still cannot get the sum of all child nodes.
myRef = myfire.getReference().child("Data").child(strUID).child("Traffic");
myRef.child("Wedding").orderByChild("stData2").equalTo("Wedding").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()) {
int sum = 0;
String value = data.child("stData4").getValue(String.class);
assert value != null;
int total = Integer.parseInt(value);
sum= sum + total;
tvBalance.setText(String.valueOf(sum));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Please give a practical example.
You're resetting the sum
for each child node. To fix this pull the sum
variable outside of the loop:
myRef = myfire.getReference().child("Data").child(strUID).child("Traffic");
myRef.child("Wedding").orderByChild("stData2").equalTo("Wedding").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
int sum = 0;
for(DataSnapshot data: dataSnapshot.getChildren()) {
String value = data.child("stData4").getValue(String.class);
assert value != null;
int total = Integer.parseInt(value);
sum = sum + total;
}
tvBalance.setText(String.valueOf(sum));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});