Android ValueFormatter引发IndexOutOfBoundsException

Android ValueFormatter引发IndexOutOfBoundsException,android,mpandroidchart,Android,Mpandroidchart,我有个小问题。我试图制作条形图的列表视图,其中xAxis表示类别,yAxis表示成本 这是我的数据。 入口 xAxis只是图表中的一个位置,我把category name作为第三个参数。然后我把它放在BarData的数组列表中 ArrayList<BarData> months = new ArrayList<>(); BarDataSet set = new BarDataSet(entries, monthName); ArrayList<IBarDataSe

我有个小问题。我试图制作条形图的列表视图,其中xAxis表示类别,yAxis表示成本

这是我的数据。 入口

xAxis只是图表中的一个位置,我把category name作为第三个参数。然后我把它放在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);
在MyValueFormatter中,我试图从条目中获取类别名称,并将其设置为xAxis值

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();
}
}
这是可行的,但有时当我滚动列表视图时,我会看到

java.lang.IndexOutOfBoundsException: Invalid index 4, size is 2.
我知道MyValueFormatter中getFormattedValue方法中的错误,但我不知道如何修复它,或者如何以正确的方式实现它?

DataSet\getEntryForIndex(int-index)

是在这里调用的错误方法<
数据集中的code>条目
存储在后备数组中,此方法将获取后备数组中该索引处的
条目
。这并不总是对应于该x值(图表上的x值)的
条目
。因此,
索引自动边界异常

您可能希望执行以下操作:

return(String)mDataSet.getEntryXPos(float value.getData()


有关详细说明,请参见

谢谢您的帮助,现在它工作正常。但在我的MPChart版本中,没有getEntryXPos方法,而是使用了getEntryForXValue。@Alexandr我很高兴它解决了您的问题。你能接受答案吗(绿色勾选)
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();
}
}
java.lang.IndexOutOfBoundsException: Invalid index 4, size is 2.