0

I had this error org.json.JSONException: Index 5 out of range [0..5) and I know what does it mean JSONArray Exception : Index 50 out of range (0..50),

my error in this code, I want to do the get last id of in json object how to do that ?

        JSONObject maxj  = peoples.getJSONObject(peoples.length());

More explenation this is the below code:

 JSONObject jsonObj = new JSONObject(myJSON);
            peoples = jsonObj.getJSONArray("result");
            System.out.println(peoples.length());

            JSONObject maxj  = peoples.getJSONObject(peoples.length());//here is the error because 
            String j_id=  maxj.getString("id");// and here

            Listitem = new ArrayList<Listitem>();
            for(int i=0;i<peoples.length();i++){
                JSONObject c = peoples.getJSONObject(i);
              //  String id ="2";
                String id=  c.getString("id");
                String url = c.getString("url");

in this code is entering a loop and getting the id ( 1,2,3,4)

                String id=  c.getString("id");

what I want only last value the max which is 4 , so how to do that?

Community
  • 1
  • 1
Moudiz
  • 7,211
  • 22
  • 78
  • 156

2 Answers2

2

The length() is 4 because there are 4 items. But indexing is from 0, so the last item will be at the index length() - 1. Thus the code should be:

peoples.getJSONObject(peoples.length() - 1);
Daniel Zolnai
  • 16,487
  • 7
  • 59
  • 71
1

As described in document also

length() Returns the number of values in this array.

JsonArray length is 4 but index will start from 0, so there will be no value for index at 4.

you need to decrease 1 from total length so peoples.length()-1 will be your solution.

Ravi
  • 34,851
  • 21
  • 122
  • 183
  • thanks , by the way is wrong if I opened two jasonobject as I explained in my code? or is there a better way ?, i will post a new question if needed – Moudiz Feb 12 '16 at 08:57
  • 1
    there is nothing wrong in it, but if you want last object from it than no need of for loop, and if you are using for loop than you can put if condition inside for loop also for last record – Ravi Feb 12 '16 at 08:59