简体   繁体   English

将(Sum)多个 Firebase 个子值加在一起得到总值?

[英]Adding (Sum) multiple Firebase child values together to give a total value?

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.我正在构建一个卡路里计数器作为 Android 应用程序的一部分,我想在前端显示每餐的总克值。 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: Firebase 层次结构:

在此处输入图像描述

To get the total number of grams that exist under each meal of each day, please use the following lines of code:要获取每天每餐下存在的总克数,请使用以下代码行:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mealsRef = rootRef.child("meals");
mealsRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            int total = 0;
            for (DataSnapshot dateSnapshot : task.getResult().getChildren()) {
                for (DataSnapshot mealSnapshot : dateSnapshot.getChildren()) {
                    String grams = mealSnapshot.child("grams").getValue(String.class);
                    total += Integer.parseInt(grams)
                }
            }
            Log.d("TAG", "total: " + total);
        } else {
            Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
        }
    }
});

According to your screenshot, the result in the logcat will be:根据您的屏幕截图,logcat 中的结果将是:

totalCalories: 320

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM