I'm trying to get a summation of a particular column within a table in my Firebase database to produce an average (to contrast with a current reading) of a value in my Android application. Just as a test, I wanted to show that sum in a TextView in my test application. When I first declare the addValueEventListener:
reff.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot snapshot2: snapshot.getChildren()){
sum = sum + snapshot2.child("age").getValue(Integer.class);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
And then make a database setValue() call and set the textView in an onClickListener, this works as expected.
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
reff.child(String.valueOf(maxid+1)).setValue(member);
Toast.makeText(MainActivity.this, "data inserted successfully", Toast.LENGTH_LONG).show();
a.setText(String.valueOf(sum));
}
});
Ultimately in my application, however, I don't want the "sum" value triggered by a button click. I want this to be present so that I can compare new data with a rolling average from my database. If I move the above code from the OnClickListener into my main onCreate method, the value for sum stays at 0. Reading various threads, I also substituted addValueEventListener() for addListenerForSingleValueEvent() but this had no impact.
Would anyone be able to suggest a way I could reformat this without having to rely on a button being pushed to get the summation from my table?