简体   繁体   中英

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?

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;
} 

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