如何避免ArrayIndexOutOfBoundsException?

时间:2013-07-22 14:54:43

标签: java android

我无法在gridview上加载图像,它总是崩溃。 log cat message“ArrayIndexOutOfBoundsException length = 16; index = 16”
这是我的代码:

public Integer[] mThumbIds = {
        R.drawable.pic_1, R.drawable.pic_2,
        R.drawable.pic_3, R.drawable.pic_4,
        R.drawable.pic_5, R.drawable.pic_6,
        R.drawable.pic_7, R.drawable.pic_8,
        R.drawable.pic_9, R.drawable.pic_10,
        R.drawable.pic_11, R.drawable.pic_12,
        R.drawable.pic_13, R.drawable.pic_14,
        R.drawable.pic_15, R.drawable.pic_16,
        R.drawable.pic_17, R.drawable.pic_18,
        R.drawable.pic_19, R.drawable.pic_20,
        ........ R.drawable.pic_96 
        };

代码:

@Override
public View getView(int position, View convertView, ViewGroup parent) { 

    int width = metrics.widthPixels / 6;
    int height = metrics.heightPixels / 6;

    ImageView i;     
        i = new ImageView(mContext);
        i.setLayoutParams(new GridView.LayoutParams(height, height));
        i.setScaleType(ImageView.ScaleType.CENTER_CROP);                         
    }

    if(mImageSet == IMAGE_SET_ONE) {           
        Integer[] images1 = new Integer[16];         
        System.arraycopy(mThumbIds, 0, images1, 0, 16);    
        i.setImageResource(images1[position]);
    } else if(mImageSet == IMAGE_SET_THREE) {

    ...........    
 }

    return i;       
}

请帮帮我..

3 个答案:

答案 0 :(得分:2)

我建议的一件事是,确保position在以下方法中小于mThubIds数组长度。数组索引从ZERO开始,如果位置大于(或)等于mThumbIds长度,您将获得ArrayIndexOutofBoundsException

@Override
public Object getItem(int position) {
    return mThumbIds[position];
}

示例:

 @Override
    public Object getItem(int position) {
        if(position < mThumbIds.length){
        return mThumbIds[position];
        }
      return null;
    }

答案 1 :(得分:0)

@Override
public Object getItem(int position) {
    if(position >= mThumbIds.length) return null;
    return mThumbIds[position];
}

请使用匈牙利表示法拍摄自己。

答案 2 :(得分:0)

Integer[] images1 = new Integer[16];         
System.arraycopy(mThumbIds, 0, images1, 0, 16);    
i.setImageResource(images1[position]);

您从Integer内的mThumbIds复制了前16个images1,但由于mThumbIds包含超过16个元素,因此position可以假设一个值介于0和mThumbIds.lenght - 1之间。当职位是16时,你得到ArrayIndexOutofBoundsExceptionYou should use i.setImageResource(mThumbIds[position]);