-1

I want to convert List of object into the json array and then pass this array on the server for submitting I tried it many times but fails I think the main issue is in the part where i can convert List of object into the json array. Kindly review the code and error and guide me thanks

try {

                        final ProgressDialog progress = new ProgressDialog(getContext());
                        progress.setTitle("Submitting Leave");
                        progress.setMessage("Loading...");
                        progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
                        progress.show();

//                        jsonObject.put("dayList",leaveDayListArrayList);

//                     JSONArray jsonArray55 = new JSONArray(utils.leaveStaEndDTOList);
                        JSONArray jsonArray33 = new JSONArray();


                     for (int j=0; j<=utils.leaveStaEndDTOList.size() ; j++ ){

                         JSONObject jsonObject1 = new JSONObject();
                         jsonObject1.put("afternoonValue",utils.leaveStaEndDTOList.get(j).getAfternoonValue());
                         jsonObject1.put("date",utils.leaveStaEndDTOList.get(j).getDate());
                         jsonObject1.put("day",utils.leaveStaEndDTOList.get(j).getDay());
                         jsonObject1.put("dayCode",utils.leaveStaEndDTOList.get(j).getDayCode());
                         jsonObject1.put("holyday",utils.leaveStaEndDTOList.get(j).getHolyday());
                         jsonObject1.put("month",utils.leaveStaEndDTOList.get(j).getMonth());
                         jsonObject1.put("morningValue",utils.leaveStaEndDTOList.get(j).getMorningValue());
                         jsonObject1.put("weekend",utils.leaveStaEndDTOList.get(j).getWeekend());
                         jsonObject1.put("year",utils.leaveStaEndDTOList.get(j).getYear());
                         jsonArray33.put(jsonObject1);

                     }

                        jsonObject.put("dayList",jsonArray33);
                        jsonObject.put("endDate",utils.creLeaveEndDate);
                   jsonObject.put("fileData","data:image/jpeg;base64,"+utils.creLeaveFile);
                        jsonObject.put("resourceId",utils.creLeaveResourceId);
                        jsonObject.put("startDate",utils.creLeaveStartDate);
                        jsonObject.put("statusId",utils.creLeaveStatusId);
                        jsonObject.put("title",utils.creLeaveTitle);
                        jsonObject.put("total",utils.creLeaveTotal);
                        jsonObject.put("typeId",utils.creLeaveTypeId);
                        jsonObject.put("year",utils.creLeaveYear);

                        //        jsonObject.put("leaveId",utils.creLeaveId);

                        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                                Request.Method.POST, "url", jsonObject, new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {

                                Toast.makeText(getContext(), "Successfully added expense", Toast.LENGTH_SHORT).show();
                                progress.dismiss();
                                final Fragment expenseFragmentList=new ExpenseFragmentList();
                                getFragmentManager().beginTransaction().replace(R.id.fragmentContainerEx,
                                        expenseFragmentList,expenseFragmentList.getClass().getSimpleName())
                                        .addToBackStack(null).commit();
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                progress.dismiss();
                                Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();

                            }
                        }
                        ){
                            @Override
                            public Map<String, String> getHeaders() {


                                Map<String, String> params = new HashMap<String, String>();
                                params.put("Accept", "application/json");
                                params.put("Authorization",utils.bear + user_token);
                                return params;
                            }
                        };

                        queue.add(jsonObjectRequest);

                    }catch (JSONException e){

                        Toast.makeText(getContext(), e.toString(), Toast.LENGTH_SHORT).show();

                    }
                }

This is my code error is shown where i pass list of object into jsonarray

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.sprintsols.Pajita, PID: 22480
    java.lang.IndexOutOfBoundsException: Invalid index 4, size is 4
        at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
        at java.util.ArrayList.get(ArrayList.java:308)
        at com.sprintsols.Pajita.Fragments.LeavesFragment$7.onClick(LeavesFragment.java:304)
        at android.view.View.performClick(View.java:5184)
        at android.view.View$PerformClick.run(View.java:20910)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:145)
        at android.app.ActivityThread.main(ActivityThread.java:5942)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Process 22480 terminated.

This is the error

{
  "dayList": [
    {
      "afternoonValue": 0,
      "date": "yyyy-MM-dd",
      "day": 0,
      "dayCode": "string",
      "holyday": true,
      "id": 0,
      "month": 0,
      "morningValue": 0,
      "weekend": true,
      "year": 0
    }
  ],
  "endDate": "yyyy-MM-dd",
  "fileData": "string",
  "leaveId": 0,
  "resourceId": 0,
  "startDate": "yyyy-MM-dd",
  "statusId": 0,
  "title": "string",
  "total": 0,
  "typeId": 0,
  "year": 0
}

and this is the json body that i want to send to the server

Mughira Dar
  • 103
  • 1
  • 1
  • 6

2 Answers2

2

Whenever you get an error, first read the error log carefully. Most of the times the issue is clearly mentioned there.

java.lang.IndexOutOfBoundsException: Invalid index 4, size is 4

For Example, here the error clearly says that you are going out of bounds of the array, i.e., trying to access an index in the array that doesn't exist.

Now, after reviewing all the array iteration, we can see that you are adding elements to a JSONArray "jsonArray33" while iterating from 0 to length. But, we know, that indexing of the list begins with 0 and goes till length-1 (not length).

So, you have to correct this:

for (int j = 0; j < utils.leaveStaEndDTOList.size(); j++)
{
     // code...
}

Hope it helps.

Suryakant Bharti
  • 673
  • 1
  • 6
  • 24
-1

for (int j=0; j<=utils.leaveStaEndDTOList.size() ; j++ ) this line should be for (int j=0; j

Mughira Dar
  • 103
  • 1
  • 1
  • 6