【问题标题】:ArrayIndexOutOfBoundsException error in parsing JSON data解析 JSON 数据时出现 ArrayIndexOutOfBoundsException 错误
【发布时间】:2015-05-22 19:51:22
【问题描述】:

我在 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&lt;10,但仍然报同样的错误。

【问题讨论】:

  • id 声明为什么?
  • Id 是一个数组?它的大小是多少?
  • 请发布 logcat 错误日志 ...
  • 谢谢,但 timrau 的回答做到了

标签: java android arrays json indexoutofboundsexception


【解决方案1】:

id 应该是一个至少包含 25 个元素的数组,以避免索引越界。

String [] id = new String[25];

【讨论】:

    【解决方案2】:

    在进入for循环之前初始化id[]数组相当于循环条件。

    或者

    在 for 循环内对数组 id[] 大小添加空检查,并初始化数组等效于循环条件。

    【讨论】:

      【解决方案3】:

      您将 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));
      }
      

      希望它会有所帮助。
      非常感谢。

      【讨论】:

      • 它给出错误 Type mismatch: cannot convert from String to String[]
      • 你的意思是 String id[]=new String[25];?
      猜你喜欢
      • 2011-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多