1

Hi all I need help with my code. I am accessing a datasnapshot of a current user logged in into firebase. I want to dynamically set the values of my bar chart with what is in the database. I set the global variables at the top of my code and set them in the anonymous inner method where I call the datasnapshot of the current user logged in. When I try set the Bar chart entrys outside this anonymous inner method it says the values are null. I have used a log and the varibales are null outside the anonymous inner method but theyre filled within it. But I cannot set the bar chart within the method please help me.You can see a Toast method in my code within that on the emulator I display the needed values of fats proteins and carbs. These values become null outside the anonymous inner method Where I need to set the new Bar chart entries.

`public class Health extends AppCompatActivity {
private TextView bmi, weight, height, fitnessGoal, fitnessLevel, calorieIntake;
private FirebaseAuth mAuth;
private BarChart barChart;
private BarData barData;
private BarDataSet barDataSet;
private ArrayList<BarEntry> barEntries = new ArrayList<>();
private Double formattedCalorieIntake;
private Double proteinAmount;
private Double carbohydrateAmount;
private Double fatAmount;
private Double proteinCalories;
private Double carbohydrateCalories;
private Double fatCalories;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_health);
    bmi = findViewById(R.id.bmiTextField);
    weight = findViewById(R.id.currentWeight);
    height = findViewById(R.id.currentHeight);
    fitnessGoal = findViewById(R.id.currentFitnessGoal);
    fitnessLevel = findViewById(R.id.fitnessLevelTextField);
    calorieIntake = findViewById(R.id.calorieIntakeTextField);
    barChart = findViewById(R.id.barChart);
    mAuth = FirebaseAuth.getInstance();
    updateFields();
    //getBarChartEntries();
    XAxis xAxis = barChart.getXAxis();
    xAxis.setValueFormatter(new IndexAxisValueFormatter(getXaxisValues()));
    barDataSet = new BarDataSet(barEntries, "Data Set");
    barData = new BarData(barDataSet);
    barChart.setData(barData);
    barDataSet.setColors(ColorTemplate.MATERIAL_COLORS);
    barDataSet.setValueTextColor(Color.BLACK);
    barDataSet.setValueTextSize(16f);

}

public void updateFields() {
    mAuth = FirebaseAuth.getInstance();
    final String userID = mAuth.getUid();
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User").child(userID);
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            User user = snapshot.getValue(User.class);
            if (user != null) {
                weight.setText(String.valueOf(user.getWeight()));
                height.setText(String.valueOf(user.getHeight()));
                fitnessGoal.setText(user.getFitnessGoal());
                Double heightInMetres = user.getHeight() / 100.00;
                Double bodyMassIndex = user.getWeight() / Math.pow(heightInMetres, 2.0);
                DecimalFormat decimalFormat = new DecimalFormat("##.00");
                Double formattedBodyMassIndex = Double.parseDouble(decimalFormat.format(bodyMassIndex));
                bmi.setText(String.valueOf(formattedBodyMassIndex));
                if (formattedBodyMassIndex < 18.5) {
                    fitnessLevel.setText("Underweight");
                } else if (formattedBodyMassIndex >= 18.5 && formattedBodyMassIndex <= 24.9) {
                    fitnessLevel.setText("Healthy Weight");
                } else if (formattedBodyMassIndex >= 25.0 && formattedBodyMassIndex <= 29.9) {
                    fitnessLevel.setText("Overweight");
                } else if (formattedBodyMassIndex > 30.0) {
                    fitnessLevel.setText("Obese");
                }
                Double weightInPounds = user.getWeight() * 2.20462;
                Double requiredCalories = 0.0;
                if (user.getActivityLevel().equals("1")) {
                    requiredCalories = weightInPounds * 14;
                } else if (user.getActivityLevel().equals("2")) {
                    requiredCalories = weightInPounds * 15;
                } else if (user.getActivityLevel().equals("3")) {
                    requiredCalories = weightInPounds * 16;
                }
                if (user.getFitnessGoal().equals("Lose Weight")) {
                    requiredCalories = requiredCalories - 500;
                } else if (user.getFitnessGoal().equals("Gain Weight")) {
                    requiredCalories = requiredCalories + 500;
                }
                formattedCalorieIntake = Double.parseDouble(decimalFormat.format(requiredCalories));
                calorieIntake.setText(String.valueOf(formattedCalorieIntake));
                if (user.getBodyType().equalsIgnoreCase("Excess body fat")) {
                    proteinAmount = (user.getWeight() * 2.20462) * 0.75;
                } else if (user.getBodyType().equalsIgnoreCase("Average Shape")) {
                    proteinAmount = (user.getWeight() * 2.20462) * 1;
                } else if (user.getBodyType().equalsIgnoreCase("Good Shape")) {
                    proteinAmount = (user.getWeight() * 2.20462) * 1.25;
                }
                if (user.getPreferredMacroNutrient().equalsIgnoreCase("Carbohydrates")) {
                    fatAmount = (user.getWeight() * 2.20462) * 0.3;
                } else if (user.getPreferredMacroNutrient().equalsIgnoreCase("Don't have a preference")) {
                    fatAmount = (user.getWeight() * 2.20462) * 0.35;
                } else if (user.getPreferredMacroNutrient().equalsIgnoreCase("Fats")) {
                    fatAmount = (user.getWeight() * 2.20462) * 0.4;
                }
                proteinCalories = proteinAmount * 4;
                fatCalories = fatAmount * 9;
                carbohydrateCalories = formattedCalorieIntake - (proteinCalories + fatCalories);
                carbohydrateAmount = carbohydrateCalories / 4;
                //values exist but not outside this method
                Toast.makeText(getApplicationContext(), "Test:" + fatAmount.floatValue() + "\n" + proteinAmount.floatValue() + "\n" + carbohydrateAmount.floatValue(), Toast.LENGTH_LONG).show();

            }
            //error coming up as null
            barEntries.add(new BarEntry(1,fatAmount.floatValue()));
            barEntries.add(new BarEntry(2, carbohydrateAmount.floatValue()));
            barEntries.add(new BarEntry(3, proteinAmount.floatValue()));
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            Toast.makeText(Health.this, "Error Occurred: " + error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

}
public ArrayList<String> getXaxisValues() {
    ArrayList<String> xLabels = new ArrayList<>();
    xLabels.add("Fats");
    xLabels.add("Fats");
    xLabels.add("Carbohydrates");
    xLabels.add("Proteins");
    ArrayList<String> label = new ArrayList<>();
    for (int i = 0; i < xLabels.size(); i++)
        label.add(xLabels.get(i));
    return label;
}`
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
ajai singh
  • 33
  • 7
  • Data is loaded from Firebase asynchronously, and your `onDataChange` is called when that loading is complete. Right now your `new BarDataSet(barEntries, "Data Set")` runs before any `barEntries.add(...)` calls. If you set breakpoints on these lines and run in the debugger, you can most easily see this. --- Any code that needs the data from the database needs to be inside `onDataChange` or be called from there. See https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519, http://stackoverflow.com/q/31700830 – Frank van Puffelen Nov 02 '20 at 15:36
  • Hi Thanks for your help I was able to follow that link and get it working – ajai singh Nov 02 '20 at 17:48
  • That's great to hear ajai. – Frank van Puffelen Nov 02 '20 at 19:24

0 Answers0