I want cumulative of production qty in key ‘pqty’ property:
JavaScript
x
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference valuesRef = rootRef.child("alldata").child("pqty");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int sum = o;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
int value = ds.getValue(Integer.class);
sum = sum + value;
}
textview15.setText(String.valueOf(sum));
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
valuesRef.addListenerForSingleValueEvent(eventListener);
I tried this and got output as 0. But I want output as 750.
I’m using sketch ware.
Advertisement
Answer
First of all, you are storing the “pqty” property in your database as a String and not as a number, which in my opinion is a really bad idea. If your data type is a number, then you should store it like that. Now, to get the desired sum, please use the following lines of code:
JavaScript
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference alldataRef = rootRef.child("alldata");
alldataRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
int sum = 0;
for (DataSnapshot ds : task.getResult().getChildren()) {
String pqty = ds.child("pqty").getValue(String.class);
sum += Integer.parseInt(pqty);
}
Log.d("TAG", "sum= " + sum);
textview15.setText(String.valueOf(sum));
} else {
Log.d(TAG, task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
According to your screenshot, the result in your logcat will be:
JavaScript
sum= 750
Things to notice:
- There’s no need for any “.child(“pqty”)” call in your “valuesRef” reference whatsoever, because you need to loop through the “DataSnapshot” object using a call to “.getChildren()” method and then get the value of “pqty” property.
- To be able to sum those values, you need to parse that String object into a number using Integer.parseInt(String s) method.
- There is no way you can get a String value from the database using “.getValue(Integer.class)”, as it will always yield an Exception. You need to get it as it’s actually stored.