user3277633 user3277633 - 2 months ago 11
Android Question

ArrayndexOutOfBounds when using Picasso and GridView

I'm learning android, and after going through the GridView example doc, I want to see if I can modify the example to use online images. I've modified the example code to below

public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(300, 300));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}


Picasso
.with(mContext)
.load(imageUrls[position])
.into(imageView);


return imageView;
}

private String[] imageUrls = {
"http://image.tmdb.org/t/p/w185/5N20rQURev5CNDcMjHVUZhpoCNC.jpg",
"http://image.tmdb.org/t/p/w185/e1mjopzAS2KNsvpbpahQ1a6SkSn.jpg",

};


However, this returns a java.lang.ArrayIndexOutOfBoundsException: length=2; index=2 error.

I understand that in the example code, the original array is an array of Integers. Could that be the problem? If that is the case, however, I don't understand how
R.drawable.sample_
objects are type Integers.

What is the best way to fix this?

Edit:

So after playing with it a bit more, it appears that the array must contain at least 22 links in order for it to not crash. If the array only contains 21 or less, the app will show the error again. Is there a reason why this gridview is restricting me to have at least 22 objects?

This is interesting because if I use the example code as it is, I can have as many or little elements I want without any error.

Answer

Make sure your getCount() method is referencing the right variable. In this case, imageUrls.

Happy coding!

Comments