简体   繁体   中英

ArrayIndexOutOfBoundsException error in parsing JSON data

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.

id应该是一个至少包含25个元素的数组,以避免索引超出范围。

String [] id = new String[25];

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM