解析 JSON 数据时出现 ArrayIndexOutOfBoundsException 错误
ArrayIndexOutOfBoundsException error in parsing JSON data
我在 id[i] = c.getString(TAG_ID);
收到 ArrayIndexOutOfBoundsException
代码如下:
for (int i = 0; i < 25; i++) {
JSONObject c = contacts.getJSONObject(i);
id[i] = c.getString(TAG_ID);
}
我检查过 JSON 文件包含 25 个对象。我也试过使用 i<10
但它仍然给出同样的错误。
您将您的 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));
}
希望对您有所帮助。
非常感谢。
id
应该是至少包含 25 个元素的数组,以避免索引越界。
String [] id = new String[25];
在进入for循环之前初始化相当于循环条件的id[]数组
或
在 for 循环内对数组 id[] 大小添加 null 检查并初始化数组等效于循环条件。
我在 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 数组声明为 -
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));
}
希望对您有所帮助。
非常感谢。
id
应该是至少包含 25 个元素的数组,以避免索引越界。
String [] id = new String[25];
在进入for循环之前初始化相当于循环条件的id[]数组
或
在 for 循环内对数组 id[] 大小添加 null 检查并初始化数组等效于循环条件。