Do while loop on object obtained from JSON parse received error: org.json.JSONException: Index 3 out of range [0..3), android studio

Do while loop on object obtained from JSON parse received error: org.json.JSONException: Index 3 out of range [0..3), android studio

我正在尝试将 Do-While 条件放入我的 jsonparse 函数中(在 adroid studio 中),但是 do-while 似乎无法正常工作。我也在用排球。我的代码如下所示。

我有多个不同的 link 需要解析。这个想法是,如果 link 中有一些 jsonobject,那么代码将 运行。否则,将弹出一条 toast 消息,指出 link 没有任何 jsonobject。

我有一些 link 没有 jsonobject,我的代码可以工作,并显示 toast 消息。

我有一些 link,其中 jsonArray 具有“显示”jsonobject,并且 totalComments > 50。然后我确实得到了信息。

问题发生 当我有一个 link 其中 jsonArray 有“显示”jsonobject,也有 totalComments,但所有的值都小于 50。在这种情况下,我希望 Do-while 循环继续检查并确保“显示”json 对象中的所有 totalComments 都小于 50。然后在检查之后在 Do-while 循环中,我想显示 Toast 消息再次显示“没有员工发表重要评论”。 但是我收到了如下所示的错误。我没有收到敬酒消息。我试图通过在我的代码周围放置 logd 消息来查明问题,但我仍然不知道问题出在哪里。我不认为我的 shuffleJsonArray 方法导致了这个问题。因为我记录了shuffledJsonArray,所以我可以看到我原来的jsonArray,除了它们是乱序的。

非常感谢您的帮助!

我的错误:

2021-06-24 11:58:18.377 3514-3514/com.example.myfirsttest W/System.err: org.json.JSONException: Index 3 out of range [0..3)
2021-06-24 11:58:18.377 3514-3514/com.example.myfirsttest W/System.err:     at org.json.JSONArray.get(JSONArray.java:293)
2021-06-24 11:58:18.377 3514-3514/com.example.myfirsttest W/System.err:     at org.json.JSONArray.getJSONObject(JSONArray.java:521)
2021-06-24 11:58:18.377 3514-3514/com.example.myfirsttest W/System.err:     at com.example.myfirsttest.AdventureActivity.onResponse(AdventureActivity.java:634)
2021-06-24 11:58:18.377 3514-3514/com.example.myfirsttest W/System.err:     at com.example.myfirsttest.AdventureActivity.onResponse(AdventureActivity.java:617)
2021-06-24 11:58:18.377 3514-3514/com.example.myfirsttest W/System.err:     at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:90)
2021-06-24 11:58:18.377 3514-3514/com.example.myfirsttest W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
2021-06-24 11:58:18.377 3514-3514/com.example.myfirsttest W/System.err:     at android.os.Handler.handleCallback(Handler.java:873)
2021-06-24 11:58:18.378 3514-3514/com.example.myfirsttest W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:99)
2021-06-24 11:58:18.378 3514-3514/com.example.myfirsttest W/System.err:     at android.os.Looper.loop(Looper.java:193)
2021-06-24 11:58:18.378 3514-3514/com.example.myfirsttest W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6669)
2021-06-24 11:58:18.378 3514-3514/com.example.myfirsttest W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
2021-06-24 11:58:18.378 3514-3514/com.example.myfirsttest W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
2021-06-24 11:58:18.378 3514-3514/com.example.myfirsttest W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2021-06-24 11:58:18.378 3514-3514/com.example.myfirsttest W/System.err: Caused by: java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
2021-06-24 11:58:18.378 3514-3514/com.example.myfirsttest W/System.err:     at java.util.ArrayList.get(ArrayList.java:437)
2021-06-24 11:58:18.378 3514-3514/com.example.myfirsttest W/System.err:     at org.json.JSONArray.get(JSONArray.java:287)
2021-06-24 11:58:18.378 3514-3514/com.example.myfirsttest W/System.err:     ... 12 more 

我的代码如下:

private void JsonParse() {

        String url = link; //jsonparse this link contain jsonarray of "display" with a lot of jsonobject inside this array

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("display");
                            arrayLength = jsonArray.length();
                            
                            int totalComments = 0;
                            String name = "no name";
                            String email = "no email";
                           

                            if (arrayLength > 0){
                                JSONArray shuffledJsonArray = shuffleJsonArray(jsonArray); //I have a method called shuffleJsonArray to shuffle the order of the jsonobject inside the "display" jsonarray.
                                

                                int i = -1;
                                do {
                                    i++;

                                    JSONObject display = shuffledJsonArray.getJSONObject(i);
                                    Log.d(TAG, "onResponse: after getting JSONobject, the result is: " + display);
                                    if (display.has("comments")) {
                                        totalComments = display.getInt("comments");
                                        Log.d(TAG, "onResponse: total comments inside checking if there is comment is: " + totalComments);
                                    } else {
                                        totalComments = 0;
                                    }
                                    Log.d(TAG, "onResponse: total comments after the check is: " + totalComments);
                                    if (totalComments > 50) {
      
                                        Log.d(TAG, "onResponse: if totalComments is > 50, then this message will be run");
                                        if (display.has("name")) {
                                            name = display.getString("name");
                                        }
                                        if (display.has("email")) {
                                            email = display.getString("email");
                                        }
                                       
                                        String info = "Name: " + name + "\n" +
                                                "email: " + email + "\n" +
                                                "total comments: " + totalComments;

                                    }

                                    Log.d(TAG, "onResponse: if totalComments < 50, then the if function is not run, so the totalComments result is: " + totalComments);

                                } while (totalComments < 50);

                                    name = "no name";
                                    email = "no email";
                                    totalComments = 0;
    

                            }else {
                                Toast toast = Toast.makeText(AdventureActivity.this, "There is no employee with significant comments", Toast.LENGTH_SHORT);
                                toast.setGravity(Gravity.CENTER, 0, 0);
                                toast.show();
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        mQueue.add(request);
    }

public static JSONArray shuffleJsonArray(JSONArray array) throws JSONException {
    // Implementing Fisher–Yates shuffle
    Random rnd = new Random();
    for (int i = array.length() - 1; i >= 0; i--) {
        int j = rnd.nextInt(i + 1);
        // Simple swap
        Object object = array.get(j);
        array.put(j, array.get(i));
        array.put(i, object);
    }
    return array;
}

org.json.JSONException: Index 3 out of range [0..3)

您遇到上述异常的原因是因为您试图访问数组中大于数组大小的索引。

根据您的代码,do...while 将 运行 直到 totalComments < 50 您的 shuffledJsonArray 不会持有 50 件物品。因此,您的数组的大小小于您要检查的条件。并且条件不合格。

请勾选

do {
    i++;
    if(i <= shuffledJsonArray.length()) {
        // Do your operations here
    } else {
        // Break the loop
        Toast.makeText(this, "Reached last position in array", Toast.LENGTH_SHORT).show;
        break;
    }
} while(totalComments < 50);