0

I am getting a string which I'm trying to convert to JSONArray. The length of the JSONArray is getting OK (if its 100 or 5000). but I am getting "java.lang.IndexOutOfBoundsException: Invalid index 50, size is 50". Below is my code.

try 
{
    JSONArray jsonArray = new JSONArray(returndResultForSNID); 
    System.out.println("jsonArray: "+jsonArray.length());
    for(int i = 0; i < jsonArray.length(); i++)
    {
        snid = jsonArray.getJSONObject(i).getString("snid");
        //number = jsonArray.getJSONObject(i).getString("phone");                   
        phoneContactsDTOArrayList.add(new PhoneContactsDTO( contactNameArr.get(i).toString() , contactPhoneNumberArr.get(i).toString(), snid, "") );                
        //System.out.println( "Could jsonArray parse malformed JSON: " + snid +" _> "+number);
    }

} 
catch (Exception e) 
{
    System.out.println( "JSONArray error: " + e.toString() );
}
RvdK
  • 19,580
  • 4
  • 64
  • 107
ani0904071
  • 362
  • 2
  • 11
  • 2
    index is starting from 0. so having collection of size 50 means that last element has 49 index – hahn Feb 10 '16 at 10:00
  • 1
    The problem is that contactNameArr or contactPhoneNumberArr is not the same size as your jsonArray. – RvdK Feb 10 '16 at 10:05

1 Answers1

0

Arrays are 0 based.

It means that an array of size 50 has index from 0 to 49.

contactNameArr and contactPhoneNumberArr are probably smaller than the size of jsonArray. In particular jsonArray has a size bigger than 51 and one of the others has a dimension of 50.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56