1

I need a help with setting a random image using setImageResource method. In the drawable folder, I have a jpeg file named photo0.jpg, photo1.jpg...photo99.jpg. And the following code works:

int p = R.drawable.photo1;
image.setImageResource(p);

The above will display photo1.jpg but I want to show a random image. I tried the following but it doesn't work.

String a = "R.drawable.photo";
int n = (int) (Math.random()*100)
String b = Integer.toString(n);
String c = a+b;
int p = Integer.parseInt(c);//checkpoint
image.setImageResource(p);

It seems like the string "R.drawable.photoXX" isn't being changed to integer at the checkpoint. Could someone please teach me a right code? Thank you in advance.

Bjarke Freund-Hansen
  • 28,728
  • 25
  • 92
  • 135
Tom Jones
  • 13
  • 1
  • 1
  • 4

2 Answers2

5

Strings are pretty much evil when it comes to work like this due to the overhead costs. Since Android already provides you with integer id's I would recommend storing all of them to an int array and then using a random number for the index.

The code would look something like this:

int imageArr[] = new int[NUM_IMAGES]; 

imageArr[1] = R.drawable.photo;

//(load your array here with the resource ids)

int n = (int)Math.random()*NUM_IMAGES;

image.setImage(imageArr[n]);

Here we have a pretty straight forward implementation and bypass all the creation and destruction that occurs with the string concats.

Sebastian Hojas
  • 4,158
  • 2
  • 27
  • 38
0

maybe the error is here

int n = (int) (Math.random()*100)

put % not * Like this

int n = (int) (Math.random()%100)

to get all numbers under 100

Farah_online
  • 561
  • 1
  • 9
  • 20