3

I am getting ArrayIndexOutOfBoundsException at id[i] = c.getString(TAG_ID);

Here's the code:

for (int i = 0; i < 25; i++) {
    JSONObject c = contacts.getJSONObject(i);
    id[i] = c.getString(TAG_ID);
}

I have checked that JSON file contains 25 objects. I have also tried using i<10 but it still gives same error.

Razib
  • 10,965
  • 11
  • 53
  • 80
Harshil Pansare
  • 1,117
  • 1
  • 13
  • 37

3 Answers3

5

id should be an array with at least 25 elements to avoid index out-of-bound.

String [] id = new String[25];
timrau
  • 22,578
  • 4
  • 51
  • 64
2

Initialize id[] array equivalent to loop condition before entering the for loop.

Or

Add null check to array id[] size inside the for loop and Initialize array equivalent to loop condition.

Rajesh
  • 2,135
  • 1
  • 12
  • 14
1

You declared your id array as -

String id[] = {null};  

That is size of your id array is 1. When you are trying to access 25th or 10th array you are getting the ArrayIndexOutOfBoundException.

Redefining your id array may help you -

String[] id = new String[25]; 

Or better you may use ArrayList then you don't have to think about the size of the array -

List<String> id = new ArrayList<String>(); //declaration of id ArrayList 

Then in your for loop you may do this -

for (int i = 0; i < 25; i++) {
    JSONObject c = contacts.getJSONObject(i);
    id.add(c.getString(TAG_ID));
}

Hope it will Help.
Thanks a lot.

Razib
  • 10,965
  • 11
  • 53
  • 80