3

I am trying to get a random image from my drawable folder, and set it in an ImageView. All the images start with "kitten" and are followed by a number, 1 through 17, which is hardcoded into the variable "kittensMax". When I run my code, it throws a NumberFormatException on the third line here. I believe the problem is that "R.drawable.kitten#" is not a number that can be "parsed" to an int, since it represents an int. Any suggestions?

Random r = new Random();
String drawableKitten = "R.drawable.kitten" + r.nextInt(kittensMax);
kittensImageView.setImageResource(Integer.parseInt(drawableKitten));
clever_trevor
  • 1,530
  • 2
  • 22
  • 42
  • 4
    [This](http://stackoverflow.com/questions/6583843/how-to-access-resource-with-dynamic-name-in-my-case) should be helpful. – A--C Jun 29 '13 at 03:29

1 Answers1

4

Try something like:

int resID = getResources().getIdentifier("kitten" + r.nextInt(kittensMax), "drawable", getPackageName());

This uses a method in the Resources class which allows you to find the ID for resources using their name, type and package name. You can see the documentation here.

It works similarly for other types or resource like id, string, raw etc. Just change the second parameter to reflect the type of resource you want.

Raghav Sood
  • 81,899
  • 22
  • 187
  • 195