I am new to android developement and I want to create android calorie calculator app, calories of food are stored inside cloud firestore. This calorie counter is made of 5 value (breakfast,lunch,dinner,consumed_calories,and daily goal). After Calories are assigned to meal, I want to sum them into variable "consumed calories" which is the sum of 3 meals (breakfast,lunch and dinner). Daily Goal is (Daily Goal - Consumed Calories). When I add one food eg. apple = 52 kcals, everything works fine, but when I add one more apple Daily Goal is = Daily Goal - 156 instead of 104, It takes value from inserted food and sum it with choosen calories.
My Code For Food Insert:
public void MealCalories(DocumentReference reference, int calories, TextView textView, String Meal) {
reference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
int meal = documentSnapshot.getLong(Meal).intValue();
meal = meal + calories;
AddData(Meal, meal, reference);
textView.setText(String.valueOf(meal));
ConsumedCalories(calories);
}
});
}
public void ConsumedCalories(int calories) {
MealRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
int breakfast = documentSnapshot.getLong("Breakfast: " + uid).intValue();
int lunch = documentSnapshot.getLong("Lunch: " + uid).intValue();
int dinner = documentSnapshot.getLong("Dinner: " + uid).intValue();
int consumed = documentSnapshot.getLong("Consumed Calories: " +uid).intValue();
consumed = breakfast + lunch + dinner ;
MealRef.update("Consumed Calories: " + uid, consumed);
daily_goal.setText(String.valueOf(consumed));
int daily_calories = documentSnapshot.getLong("Daily Goal: " + uid).intValue();
daily_calories = daily_calories - consumed;
MealRef.update("Daily Goal: "+ uid,daily_calories);
}
});
}
Daily Goal was supposed to be 1896.
It appears that your code is fetching the consumed value from the snapshot, and then immediately overwriting it:
int consumed = documentSnapshot.getLong("Consumed Calories: " +uid).intValue();
consumed = breakfast + lunch + dinner ;
Is this intentional? Should it be consume += breakfast... etc?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.