I’m trying to generate a random animation to load for an ImageView. It works, but only sometimes. After three animations are picked, it will throw an ArrayIndexOutOfBoundsException and I’m not sure why. If I catch the Exception, three animations will be picked at random, then none will load.
final int[] anim = { R.anim.anim_0, R.anim.anim_1, R.anim.anim_2,
R.anim.anim_3, R.anim.anim_4, R.anim.anim_5 };
Random ran = new Random();
int i = ran.nextInt(6 - 1);
mAlbum.startAnimation(AnimationUtils.loadAnimation(
getBaseContext(), anim[i++]));
Try
anim[ran.nextInt(anim.length)]instead. This will choose a number from zero (inclusive) to the number of elements in the array (exclusive) and will prevent the exception.