I am building a calorie counter as part of an Android application and I would like to display the total Grams value of each meal in the front-end. So far I am only retrieving a single child value. How would I add a value to the total amount when a new meal is added?
FoodFragment
mealRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
ds.getKey();
long sum = 0;
String grams = ds.child("grams").getValue(String.class);
if (grams == null) {
textViewFoodCounter.setText("0");
} else {
sum = sum + Integer.parseInt(grams);
textViewFoodCounter.setText(String.valueOf(sum));
}
progressBar.setMax(1000); // make dynamic
ObjectAnimator.ofInt(progressBar, "progress", Integer.parseInt(grams))
.setDuration(300)
.start();
Meal data = ds.getValue(Meal.class);
meals.add(data);
}
foodAdapter = new FoodAdapter(meals);
foodRecyclerView.setAdapter(foodAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
AddNewMeal
logMeal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String foodName = mealName.getText().toString().trim();
String calories = caloriesET.getText().toString().trim(); // potentially make this an integer?
String grams = gramsET.getText().toString().trim(); // potentially make this an integer?
meal = new Meal(grams, foodName, calories);
databaseReference.child("meals").child(dateString).push().setValue(meal)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Log.d("Event", "onComplete: Successfully added event information to Dog");
progressBar.setVisibility(View.GONE);
Toast.makeText(AddNewMeal.this, "Successfully added new meal", Toast.LENGTH_LONG).show();
} else {
Log.d("Event", "Failure - Dog not Created", task.getException());
progressBar.setVisibility(View.GONE);
Toast.makeText(AddNewMeal.this, "Meal not added, please try again..", Toast.LENGTH_LONG).show();
}
}
});
});
Firebase Hierarchy: