I am trying to clear an anyChart in onCreate before I call a method that sets it. The reason for doing so is because I am using a tabbed activity and everytime I go in and out of the activity and come back it duplicates my piechart. I have investigated how to do so but I get this error when I add the following two lines in on create before any method call Solution attempt ->
- anyChart.clear();
- anyChart.invalidate();
Error caused by solution -> Attempt to invoke virtual method 'java.lang.String com.anychart.core.Chart.getJsBase()' on a null object reference
public class Remember extends Fragment {
private AnyChartView anyChartView;
private TextView calories, fats, proteins, carbohydrates;
private final FirebaseAuth mAuth = FirebaseAuth.getInstance();
private final String userID = mAuth.getUid();
private double macroCalories, macroProteins, macroFats, macroCarbohydrates;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_monday, container, false);
anyChartView = view.findViewById(R.id.pieChart);
calories = view.findViewById(R.id.dailyCaloriesLeftTextView);
fats = view.findViewById(R.id.dailyFatsTV);
proteins = view.findViewById(R.id.dailyProteinsTV);
carbohydrates = view.findViewById(R.id.dailyCarbsTV);
anyChartView.clear();
anyChartView.invalidate();
setUpTextFields();
return view;
}
public void setUpTextFields() {
assert userID != null;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Macros").child(userID);
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
Macro macro = snapshot.getValue(Macro.class);
assert macro != null;
calories.setText(String.valueOf(macro.getCalorieConsumption()));
fats.setText(String.valueOf(macro.getFats()));
proteins.setText(String.valueOf(macro.getProteins()));
carbohydrates.setText(String.valueOf(macro.getCarbohydrates()));
macroFats = macro.getFats();
macroProteins = macro.getProteins();
macroCarbohydrates = macro.getCarbohydrates();
setUpPieChart(macroFats,macroProteins,macroCarbohydrates);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(getContext(), "Error Occurred!" + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void setUpPieChart(double fats,double proteins,double carbohydrates) {
String[] macros = new String[]{"Fat", "Protein", "Carbs"};
Pie pie = AnyChart.pie();
List<DataEntry> dataEntries = new ArrayList<>();
double[] macrosValues = {fats, proteins, carbohydrates};
for (int i = 0; i < macros.length; i++) {
dataEntries.add(new ValueDataEntry(macros[i], macrosValues[i]));
}
pie.data(dataEntries);
anyChartView.setChart(pie);
}
}