android JSONException 索引超出范围

Posted

技术标签:

【中文标题】android JSONException 索引超出范围【英文标题】:android JSONException index out of range 【发布时间】:2019-04-16 14:28:20 【问题描述】:

我的数据库中有 3 条记录,但只有一条显示。不知道如何解决这个问题,我尝试了一切。帮助

public void onResponse(JSONArray response) 
    JSONObject jo;
    Teacher teacher;

    try 
        for (int i = 0; i < response.length(); i++) 
            JSONArray innerJsonArray = response.getJSONArray(i);
            jo = innerJsonArray.getJSONObject(i);

            int id = jo.getInt("id");
            String name = jo.getString("teacher_name");
            String description = jo.getString("teacher_description");
            String imageUrl = jo.getString("teacher_image_url");

            teacher = new Teacher(name, description, php_mysql_SITE_URL+imageUrl);
            teachers.add(teacher);
            te.setText(Integer.toString(response.length()));
        
        //SET SPINNER
        adapter = new ListViewAdapter(c, teachers);
        gv.setAdapter(adapter);

【问题讨论】:

错误表示您正在尝试访问超出数组大小范围的值,您可以发布完整的 logcat 错误吗? 应该有 2 个 for 循环,一个用于 'JSONArray innerJsonArray = response.getJSONArray(i);'第二个是'JSONArray innerJsonArray = response.getJSONArray(j);'遍历innerJsonArray 你能发布你试图解析的 JSON 吗? 当我检查 responce.leght() 它告诉我它的 1。似乎我只得到 1 条记录,但是当我在网络上运行 php 时它给了我所有 3 个文件 【参考方案1】:

应该有 2 个 for 循环,一个用于 JSONArray innerJsonArray = response.getJSONArray(i);,第二个用于 JSONArray innerJsonArray = response.getJSONArray(j);,通过 innerJsonArray 进行迭代

public void onResponse(JSONArray response) 

        JSONObject jo;
        Teacher teacher;

        try 

        for (int i = 0; i < response.length(); i++) 
            JSONArray innerJsonArray = response.getJSONArray(i);
                for (int j = 0; j < innerJsonArray.length(); j++) 
                     jo = innerJsonArray.getJSONObject(j);
                     int id = jo.getInt("id");
                     String name = jo.getString("teacher_name");
                     String description = jo.getString("teacher_description");
                     String imageUrl = jo.getString("teacher_image_url");
                     teacher = new Teacher(name, description, PHP_MYSQL_SITE_URL + imageUrl);
                     teachers.add(teacher);
                     te.setText(Integer.toString(response.length()));
                
               
               //SET SPINNER
        adapter = new ListViewAdapter(c, teachers);
        gv.setAdapter(adapter);
        
    

【讨论】:

@Dadran 它奏效了,一整天都这样。谢谢 1000000000000 @noob 非常欢迎您:D 因为它有效,请点击勾选标记接受我的解决方案 第一次对不起。我该怎么做??

以上是关于android JSONException 索引超出范围的主要内容,如果未能解决你的问题,请参考以下文章

JSONException 故障排除:在字符 0 Android 处输入结束

Android - 在没有堆栈跟踪的情况下调用 getJSONArray 抛出 JSONException

JSONException:名称必须是字符串

Android Studio, Firebase W/System.err: org.json.JSONException: Index 0 out of range [0..0)

类型 org.json.JSONException 被定义多次

JSONException:Java.lang.String 类型的值 <?xml 无法转换为 JSONObject