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.

4
  • 3
    What is id declared as? Commented Mar 19, 2015 at 15:44
  • 1
    Id is an array ? What is the size of it? Commented Mar 19, 2015 at 15:44
  • pls post logcat error log ... Commented Mar 19, 2015 at 15:47
  • thanks but timrau's answer did it Commented Mar 19, 2015 at 15:57

3 Answers 3

5

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

String [] id = new String[25];
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

2 Comments

It gives error as Type mismatch: cannot convert from String to String[]
did you meant String id[]=new String[25];?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.