使用数组中的数据为 MPAndroid 条形图提供数据

Feeding MPAndroid Bar Chart with data from an array

我正在使用此方法从 firebase 获取数据:

        DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
        DatabaseReference eventIdRef = rootRef.child("points");
        ValueEventListener eventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                List<Integer> count = new ArrayList<>();
                List<String> names = new ArrayList<>();
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    final String Sname = ds.child("symptomName").getValue(String.class);
                    final Integer counter = ds.child("patientsCounter").getValue(Integer.class);
                    
                    count.add(counter);
                    names.add(Sname);
                   
                    DataPoint dataPoint = ds.getValue(DataPoint.class);
                    dataValues1(count , Sname);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {}
        };
        eventIdRef.addListenerForSingleValueEvent(eventListener);

来自 firebase 的数据(symptomName 和 counter)应该使用 MPAndroidChart 分别作为 x 轴和 y 轴绘制条形图。我有这个,但它不起作用 :

        barChart = findViewById(R.id.mp_BarChart);
        BarDataSet barDataSet1 = new BarDataSet((Sname, counter), "Dataset 1");
        barDataSet1.addColor(Color.BLUE);
        BarData barData = new BarData();
        barData.addDataSet(barDataSet1);
        barChart.setData(barData);
        barChart.invalidate();

是否可以将数据从 firebase 直接传递到图表?

这一行之前:

BarDataSet barDataSet1 = new BarDataSet((Sname, counter), "Dataset 1");

您需要添加:

BarEntries barEntries = new ArrayList<BarEntry>();

for (int i = 0; i < names.size(); i++) {
barEntries.add(new BarEntry(names[i], counter[i]));
}

然后你需要替换这一行:

BarDataSet barDataSet1 = new BarDataSet((Sname, counter), "Dataset 1");

这一行:

BarDataSet barDataSet1 = new BarDataSet(barEntries, "Dataset 1");