Michiru
Michiru

Reputation: 179

ArrayIndexOutOFBoundsException in a List Android

I have an ArrayIndexOutOfBoundsException

private Size getPictureSize() {
    List<Size> list = camera.getParameters().getSupportedPictureSizes();
        int i = 0;
    for (Size size : list) {
        if (Math.min(size.width, size.height) <= 800) {
            if (Math.max(size.width, size.height) > 800) {
                return size;
            } else {

                return (i > 0 ? list.get(i - 1) : list.get(0));
            }
        }
        i++;

    }

    return list.get(0);
}

This is part an application someone asked me to test after he put it on the market and one of the error report was this one at line

return (i > 0 ? list.get(i - 1) : list.get(0));

I know what this exception means but what could cause it?

Upvotes: 1

Views: 190

Answers (1)

Tiago Pasqualini
Tiago Pasqualini

Reputation: 821

You have a couple of problems in your code:

  • this line: return (i > 0 ? list.get(i - 1) : list.get(0)); may calculate an index that does not exist in your list;
  • the last line of your code (return list.get(0);) may raise an IndexOutOfBoundsException if your list is empty.

I changed your code to fix these problems. See if it solves your problem:

private Size getPictureSize() {
    List<Size> list = camera.getParameters().getSupportedPictureSizes();
    Size prevSize = null;
    for (Size size : list) {
        if (Math.min(size.width, size.height) <= 800) {
            if (Math.max(size.width, size.height) > 800) {
                return size;
            } else {
                return (prevSize == null? size : prevSize);
            }
        }
        prevSize = size;
    }

    if(list.size() > 0) {
        return list.get(0);
    }

    return null;
} 

Upvotes: 1

Related Questions