Search code examples
androidfirebasefirebase-realtime-databasetextview

Do calculation by retrieving data from Child Node is not working at all in Android Studio/Firebase


I have a problem to do subtract calculation by retrieving data from a Child Nod. As you can see my layout below, what I want to do is to get Remaining Kcal value by calculating Daily Kcal value minus Total Kcal and display the Remaining Kcal to the TextView.

layout

I suspected the calculation for the subtraction part (code below) is not working at all as I tried to put the remainingCount/remainingCalorie value into firebase but nothing happened.

 //CALCULATE AND DISPLAY REMAINING CALORIE
    private void updateRemainingKcal(final double finalCount) {

        DatabaseReference userRecord = FirebaseDatabase.getInstance().getReference();
        DatabaseReference userReference = userRecord.child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
        userReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                double remainingCount = 0;

                for (DataSnapshot userChild: dataSnapshot.getChildren()) {
                    for (DataSnapshot recordSnapshot: userChild.getChildren()) {
                        double userCalorie = Double.valueOf(recordSnapshot.child("daily calorie").getValue(String.class));
                        remainingCount = userCalorie - finalCount;
                        userRemainingCalorie.setText((remainingCount  +"kcal"));

                        myHistoryRef = FirebaseDatabase.getInstance().
                                getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                                .child(date_record).child("Total Calorie");

                        Map<String, Object> values = new HashMap<>();
                        values.put("remainingCalorie", remainingCount);

                        myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                            }
                        });
                    }
                }
                Log.d("TAG", remainingCount + "");
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                throw databaseError.toException();
            }
        });
    }

This is relevant code to do this operation, whereby I need to retrieve "daily calorie' from User first, then I can do the substraction daily calorie (Required Kcal) - total calorie consume (Total Kcal) = Remaining Calorie (Remaining Kcal):



        //**********************DATABASE REFERENCE FOR USER REQUIRED CALORIE***************************//
        requiredCalorieRef = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
        requiredCalorieRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {


                String userCalorieSuggestion = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
                userRequiredCalorie.setText((userCalorieSuggestion  +"kcal"));


            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }

        });

    //CALCULATE AND DISPLAY TOTAL CALORIE ACCORDING TO DATE
    private void updateTotalCalorie(final String date_n) {

        DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
        DatabaseReference nameRef = rootRef.child("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(date_record);
        nameRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                double count = 0;
                for (DataSnapshot foodTypeSnapshot: dataSnapshot.getChildren()) {
                    for (DataSnapshot recordSnapshot: foodTypeSnapshot.getChildren()) {
                        double foodCalorie = Double.valueOf(recordSnapshot.child("foodCalorie").getValue(String.class));
                        count = count + foodCalorie;
                        userTotalCalorie.setText((count  +"kcal"));


                        myHistoryRef = FirebaseDatabase.getInstance().
                                getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                                .child(date_record).child("Total Calorie");

                        Map<String, Object> values = new HashMap<>();
                        values.put("totalCalorie", count);
                        values.put("Date Consume", date_n);

                        final double finalCount = count;
                        myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                updateRemainingKcal(finalCount);
                            }
                        });


                    }
                }
                Log.d("TAG", count + "");
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                throw databaseError.toException();
            }
        });



    }

    //CALCULATE AND DISPLAY REMAINING CALORIE
    private void updateRemainingKcal(final double finalCount) {

        DatabaseReference userRecord = FirebaseDatabase.getInstance().getReference();
        DatabaseReference userReference = userRecord.child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
        userReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                double remainingCount = 0;

                for (DataSnapshot userChild: dataSnapshot.getChildren()) {
                    for (DataSnapshot recordSnapshot: userChild.getChildren()) {
                        double userCalorie = Double.valueOf(recordSnapshot.child("daily calorie").getValue(String.class));
                        remainingCount = userCalorie - finalCount;
                        userRemainingCalorie.setText((remainingCount  +"kcal"));

                        myHistoryRef = FirebaseDatabase.getInstance().
                                getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                                .child(date_record).child("Total Calorie");

                        Map<String, Object> values = new HashMap<>();
                        values.put("remainingCalorie", remainingCount);

                        myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                            }
                        });
                    }
                }
                Log.d("TAG", remainingCount + "");
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                throw databaseError.toException();
            }
        });
    }




This is my firebase looks like - there is no node of RemainingCalorie at all at History node: firebase

How can I solve this issue despite knowing the problem. I have tried several ways but nothing could help to solve this code problem.


Solution

  • I have solved my own problem. Thank you, finally did it. This is right code for those who have same problem in future:

    private void updateRemaining(final int finalCount) {
        userDatabase = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
        userDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                String user = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
                int dailyCalorie = Integer.parseInt(user);
                int remainingCalorie = dailyCalorie-finalCount;
                userRemainingCalorie.setText((remainingCalorie  +"kcal"));
    
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                throw databaseError.toException();
            }
    
        });
    }
    

    this is the screen-shot enter image description here