0

I'm trying to update the AnyChart pie chart with data provided through an input field, I want to have the pie chart update to reflect the added data.

Here's my code:

//Initialize the PieChart
    AnyChartView anyChartView;

    //Data Structures for Pie Chart
    List<String> drinks = new ArrayList<>(Arrays.asList("Water", "Orange Juice", "Pepsi"));
    List<Double> quantity = new ArrayList<>(Arrays.asList(50.5,20.2,15.2));

    //Input fields
    EditText drinkNameInput;
    EditText drinkAmountInput;
    //Button
    Button addDrinkButton;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intakechart);

        drinkNameInput = findViewById(R.id.drinkNameArea);
        drinkAmountInput = findViewById(R.id.drinkAmountArea);
        addDrinkButton = findViewById(R.id.addDrinkButton);

        anyChartView = findViewById(R.id.any_chart_view);

        Pie pie = AnyChart.pie();

        List<DataEntry> dataEntries = new ArrayList<>();

        for(int i = 0; i < drinks.size(); i++)
            dataEntries.add(new ValueDataEntry(drinks.get(i), quantity.get(i)));

        pie.data(dataEntries);
        anyChartView.setChart(pie);

        addDrinkButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                dataEntries.add(new ValueDataEntry(
                    drinkNameInput.getText().toString(),
                    Double.parseDouble(drinkAmountInput.getText().toString())
                ));

                Log.v("Data: ", dataEntries.toString());
            }
        });
    }

Whenever I add to the drinks and quantity lists from the inputted data, the pie chart does not update to reflect the changes. The lists however do contain the added drink and amount, so I know the button onClickListener is working. Does anyone see what's wrong?

Stephen
  • 85
  • 5

1 Answers1

0

Your chart has no reference to drinks or quantity. You will need to hold global reference to your dataEntries list and update that instead.

private List<DataEntry> dataEntries = new ArrayList<>();

public void onClick(View view) {
    dataEntries.add(new ValueDataEntry(
            drinkNameInput.getText().toString(),
            Double.parseDouble(drinkAmountInput.getText().toString())));
    pie.data(dataEntries);
}
Dan Harms
  • 4,725
  • 2
  • 18
  • 28
  • I reformatted my code and removed the setPieChart method and initialized everything in the onCreate method. I employed the changes you suggested and it still didn't update the chart. I added a Log.v to see if the dataEntries is taking on the new values and it is, the pie chart is just not updating. – Stephen May 18 '22 at 03:49
  • I updated my answer to include a part I missed. You have to call `pie.data(dataEntries)` each time the data changes. – Dan Harms May 18 '22 at 04:58