尝试将RowItem添加到ListView时,Android IndexOutOfBoundsException

时间:2017-07-26 15:42:15

标签: java android json listview

我正在尝试从JSON对象中提取一些数据以插入添加到ListView的CustomRowItem,JSON被提取得很好但是当我尝试将数据添加到行项时我得到了我:{{ 1}}错误。

完整代码如下:

D/ERROR: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

代码在 protected void parseJsonToCurrencyRowItem(Currency cryptoCurrency) { try { for (int i = 0; i < returnedJsonArrayResult.length(); i++) { JSONObject jOb = returnedJsonArrayResult.getJSONObject(i); cryptoCurrency.jsonCurrencyName.add(jOb.getString("name")); cryptoCurrency.jsonCurrencyName.add(jOb.getString("percent_change_24h")); cryptoCurrency.jsonCurrencyName.add(jOb.getString("price_gbp")); cryptoCurrency.jsonCurrencyName.add(jOb.getString("24h_volume_gbp")); drawListRows(cryptoCurrency, i); } } catch (Exception e) { Log.d("ERROR", e.toString()); } } protected void drawListRows(Currency currency, int i) { CurrencyRowItem item = new CurrencyRowItem(currency.jsonCurrencyName.get(i), currency.jsonCurrencyPrice.get(i), currency.jsonPercentchange24hr.get(i), currency.jsonVolume24hr.get(i)); rowItemList.add(item); adapter.notifyDataSetChanged(); } 失败 Line和它在试图解决这个问题时尽力而为,感谢您的帮助。

AdapterCode

CurrencyRowItem item = new CurrencyRowItem(currency.jsonCurrencyName.get(i), currency.jsonCurrencyPrice.get(i), currency.jsonPercentchange24hr.get(i), currency.jsonVolume24hr.get(i));

2 个答案:

答案 0 :(得分:1)

我想它应该是这样的:

cryptoCurrency.jsonCurrencyName.add(jOb.getString("name"));
        cryptoCurrency.jsonCurrencyPercent.add(jOb.getString("percent_change_24h"));
        cryptoCurrency.jsonCurrencyPrice.add(jOb.getString("price_gbp"));
        cryptoCurrency.jsonCurrencyVolume.add(jOb.getString("24h_volume_gbp"));

你没有填充数据,这个数组可能是空的

答案 1 :(得分:0)

你的数组是空的。

D/ERROR: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 

尝试添加此内容:

if (returnedJsonArrayResult != null && 
    !returnedJsonArrayResult.isEmpty()) {
    for (int i = 0; ...) {
        // your code
    }
}

此外,将循环整数设置为0,而不是1.数组基于0。如果你从一开始,你将总是跳过第一个条目。