![](/img/trans.png)
[英]JsonParser ArrayIndexOutOfBoundsException when parsing json
[英]ArrayIndexOutOfBoundsException error in parsing JSON data
我在id[i] = c.getString(TAG_ID);
获得ArrayIndexOutOfBoundsException id[i] = c.getString(TAG_ID);
这是代码:
for (int i = 0; i < 25; i++) {
JSONObject c = contacts.getJSONObject(i);
id[i] = c.getString(TAG_ID);
}
我检查过JSON文件包含25个对象。 我也尝试过使用i<10
但它仍然会出现同样的错误。
id
应该是一个至少包含25个元素的数组,以避免索引超出范围。
String [] id = new String[25];
在进入for循环之前初始化id []数组,等效于循环条件。
要么
将null检查添加到for循环内的数组id []大小和Initialize数组等效于循环条件。
你声明你的id数组为 -
String id[] = {null};
这是您的id数组的大小是1.当您尝试访问第25或第10个数组时,您将获得ArrayIndexOutOfBoundException
。
重新定义您的id
数组可能会帮助您 -
String[] id = new String[25];
或者你可以使用ArrayList
然后你不必考虑数组的大小 -
List<String> id = new ArrayList<String>(); //declaration of id ArrayList
然后在你的for循环中你可以这样做 -
for (int i = 0; i < 25; i++) {
JSONObject c = contacts.getJSONObject(i);
id.add(c.getString(TAG_ID));
}
希望它会有所帮助。
非常感谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.