Reputation: 591
I have a small problem. I'm trying to make a listView of BarCharts, where xAxis represents categories, and yAxis - cost.
Here is my data. entry
entries.add(new BarEntry(xAxis, cost, categoryName));
xAxis is just a position in chart, I put category name as 3rd parameter. Then I put it in array list of BarData
ArrayList<BarData> months = new ArrayList<>();
BarDataSet set = new BarDataSet(entries, monthName);
ArrayList<IBarDataSet> dataSets = new ArrayList<>();
dataSets.add(set);
BarData barData = new BarData(dataSets);
months.add(barData);
Then in adapter I set value formatter
BarData data = getItem(position);
...
xAxis.setValueFormatter(new MyValueFormatter(data.getDataSetByIndex(0)));
and in MyValueFormatter I'm trying to get category name from entry and set it as xAxis value.
public class MyValueFormatter implements IAxisValueFormatter {
private IBarDataSet mDataSet;
public StatisticByMonthValueFormatter(IBarDataSet data) {
mDataSet = data;
}
@Override
public String getFormattedValue(float value, AxisBase axis) {
return (String) mDataSet.getEntryForIndex((int) value).getData();
}
}
This woks, but sometimes when I'm scrolling list view I get
java.lang.IndexOutOfBoundsException: Invalid index 4, size is 2.
I know, that bug in the getFormattedValue method in MyValueFormatter, but i don't understand how can I fix this, or how implement this in the right way?
Upvotes: 1
Views: 1141
Reputation: 21447
DataSet#getEntryForIndex(int index)
is the wrong method to call here. Entry
in a DataSet
are stored in a backing array and this method will get the Entry
at that index in the backing array. This doesn't always correspond to the Entry
for that x-value (the x-value on the chart). Hence, the IndexOutOfBoundsException
.
You would want to do something this instead:
return (String) mDataSet.getEntryXPos(float value).getData();
See the javadoc for DataSet for further explanation
Upvotes: 3