ValueFormatter抛出IndexOutOfBoundsException

时间:2017-03-24 13:12:30

标签: android mpandroidchart

我有一个小问题。我试图制作一个BarCharts列表视图,其中xAxis代表类别,yAxis代价。

这是我的数据。 条目

lista = [ {'uid': 'test_subject145', 'class':'?',  'data':[  {'chunk':1, 'writing':[ ['this is exciting'],[ 'you are good' ]... ]}  ]  },
          {'uid': 'test_subject166', 'class':'?',  'data':[  {'chunk':2, 'writing':[ ['he died'],[ 'go ahead' ]... ]}  ] }, ...]

list_of_final_products = []

for itema in lista:
  try:
    for data_item in itema['data']:
      for writa in data_item['writing']:
        for writa_itema in writa:
          list_of_final_products.append(writa)
  except:
    pass

xAxis只是图表中的一个位置,我将类别名称作为第三个参数。然后我把它放在BarData的数组列表中

entries.add(new BarEntry(xAxis, cost, categoryName));

然后在适配器中设置值格式化程序

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值。

BarData data = getItem(position);
...
xAxis.setValueFormatter(new MyValueFormatter(data.getDataSetByIndex(0)));

这是炒作,但有时当我滚动列表视图时,我得到了

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();
}
}

我知道,MyValueFormatter中的getFormattedValue方法中存在错误,但我不明白如何解决这个问题,或者如何以正确的方式实现这一点?

1 个答案:

答案 0 :(得分:2)

DataSet#getEntryForIndex(int index)

这是在这里打电话的错误方法。 Entry中的DataSet存储在后备数组中,此方法将在后备数组中的该索引处获得Entry。这并不总是对应于该x值的Entry(图表上的x值)。因此,IndexOutOfBoundsException

你可能想要做一些事情:

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

有关详细说明,请参阅javadoc for DataSet

相关问题