-2

i can't load images on gridview, it always crashes. log cat message "ArrayIndexOutOfBoundsException length=16 ; index=16"
here is my code :

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

code :

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

Please help me..

Paul Nababan
  • 11
  • 1
  • 4

3 Answers3

2

One thing I would suggest is, make sure position is less than mThubIds array length in following method. Array index starts from ZERO, if position is greater (or) equal to mThumbIds length, you will get ArrayIndexOutofBoundsException.

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

Example:

 @Override
    public Object getItem(int position) {
        if(position < mThumbIds.length){
        return mThumbIds[position];
        }
      return null;
    }
kosa
  • 65,990
  • 13
  • 130
  • 167
0
@Override
public Object getItem(int position) {
    if(position >= mThumbIds.length) return null;
    return mThumbIds[position];
}

Please shoot yourself for using hungarian notation.

Pete B.
  • 3,188
  • 6
  • 25
  • 38
0
Integer[] images1 = new Integer[16];         
System.arraycopy(mThumbIds, 0, images1, 0, 16);    
i.setImageResource(images1[position]);

you copy the first 16 Integer, from mThumbIds inside images1, but since mThumbIds containse more than 16 elements your position can be assume a value between 0 and mThumbIds.lenght - 1 . When position is 16 you get your ArrayIndexOutofBoundsException. You should use i.setImageResource(mThumbIds[position]);

Blackbelt
  • 156,034
  • 29
  • 297
  • 305