Android JSONException索引超出范围

时间:2018-11-13 17:17:28

标签: android json arraylist

我的数据库中有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);

1 个答案:

答案 0 :(得分:0)

应该有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);
        }
    }