Why does ArrayIndexOutOfBoundsException occur and how to avoid it in Android? [closed]
Why does ArrayIndexOutOfBoundsException
occur and how to avoid it in Android?
Solution 1:
This exception is thrown when you try to access an array item that doesn't exist:
String [] myArray = new String[2];
myArray[2] = "something"; // Throws exception
myArray[-1] = "something"; // Throws exception
You should check that your index is not negative and not higher than the array length before accessing an array item.
Solution 2:
Why does ArrayIndexOutOfBoundsException occur [...]
Here is a quotation from the Java Language Specification: 10.4 Array Access:
All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown.
[...] and how to avoid it in Android?
You make sure you're indices are within the range [0...yourArray.length
-1].
(Note the -1 above. Arrays are 0-indexed which means that you'll find the first element at index 0, and the last at length-1.)