I am using a random number to set my imageButton to a random image. I am wondering if there is a way to use the random int in the file path for the drawable. This code gives a run time error for invalid integer but will compile.
Random generator = new Random();
int chooseFirstPicture = generator.nextInt(2);
int imagePath1 = Integer.parseInt("R.drawable.image" + chooseFirstPicture);
btn1.setBackgroundResource(imagePath1);
You are parsing a String to a Integer, so your code is going to throw a NumberFormatException every time you run it.
The correct way to get a resource id from a String key is using the function getIdentifier():
Random generator = new Random();
int chooseFirstPicture = generator.nextInt(2);
int resourceId = getResources().getIdentifier("image" + chooseFirstPicture, "drawable", getPackageName());
if (resourceId != 0) {
//Provided resource id exists in "drawable" folder
btn1.setBackgroundResource(imagePath1);
} else {
//Provided resource id is not in "drawable" folder.
//You can set a default image or keep the previous one.
}
You can find more information in the Android Resources class documentation.
Hm.. You trying to convert "R.drawable.image1" string to an integer that is impossible. During compilation nothing checks what's in the string, but when you run the app, it fails immediately.
Better to use the getResources().getIdentifier() with proper parameters (link)
I hope it helps :)
Related
I have few images in my app ( they are all copied into res/drawable and have appropriate R.drawable reference) that I want to assign them to my ImageViews using contents of an string type variable. To illustrated, I have an image file named "c4.png" in my drawable folder and an string variable (card) that contains "c4". I want to see if there is any way I can use a code like this (ImageView1.setImageResource(R.drawable.card)) to assign image c4 to my ImageView1 instead of using ImageView1.setImageResource(R.drawable.c4). Basically, I am wondering if it is possible to replace a variable with the specific image name in the R.drawable.resourceName. I know that R.drawable.resourceName is an integer and I am not trying to change its type. I want to replace the resourceName with a variable. I appreciate any help
Use this to draw a random number in particular range-
int min = 0;
int max = 9;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
Then using this number pick image from image array-
public Integer[] nImages = {
R.drawable.c1, R.drawable.c2,
R.drawable.c3, R.drawable.c4,
R.drawable.c5, R.drawable.c6,
R.drawable.c7, R.drawable.c8,
R.drawable.c9, R.drawable.c10
};
ImageView1.setBackgroundResource(nImages [i1]);
Hope this works.
Try this
Resources res = getResources();
int id = res.getIdentifier(card, "drawable", getPackageName());
img.setImageResource(id);
this may solve your problem.
Or you can put the images in the asset folder. Assets are referenced by their filename, as in
getAssets().open(<filename>);
This returns an InputStream. Afterwhich it is trivial to convert them to a Bitmap resource
BitmapFactory.decodeStream(inputStream);
And then use that bitmap for your ImageView. That should be straightforward with
imageView.setImageBitmap(bitmap);
I want to replace the resourceName with a variable.
Instead of declaring the variable card as a string declare it as an Integer. So that you can use it like the following.
int card=R.drawable.c4;
ImageView1.setImageResource(card);
You probably can not do something like R.drawable.card because the R file is generated according to the resources in the drawable folder.
hope this helps
I have code like tthis:
String s = "replace__menu__" + data.imageid + ".png";
int RID = this.getApplicationContext().getResources().getIdentifier(s, "drawable-hdpi", getPackageName());
The String s = instruction sets a value that is the same as one of names in my res/drawable-hdpi folder. However, the returned value sets RID to the value 0
Any idea why my code is not working? Am I doing something wrong?
Try this
String s = "replace__menu__" + data.imageid; // image name is needed without extention
int RID = this.getApplicationContext().getResources().getIdentifier(s, "drawable", getPackageName());
".png" is not part of a ressource name
"drawable-hdpi" I would try just 'drawable' instead
I have an arraylist of strings, I need to randomly select an index and if the string value was
"bear", then set background of button to bear.jpg.
OK, my research shows that resources are accessed by an int id, not their name, I am not sure the best way to achieve what I want to do. Here is my code:
list.add("alligator");
list.add("bear");
list.add("beaver");
list.add("bison");
randomInt = randomGenerator.nextInt(list.size());
b1.setBackgroundResource(R.drawable.list.get(randomInt));
Now of course the last line of the code is wrong, I wrote it to show what I want to achieve. My latest attempt to accomplish this was trying to get the resource id and access the resource this way, but I don't know if this is the way to do this, and if it is I am not using the correct code. I am trying hard to do this by myself but I could use some advice on what to do here. Here is my attempt:
String mDrawableName = "bear";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
String s= Integer.toString(resID);
Use the below code
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
b1.setBackgroundResource(resID);
Try this:
list.add("alligator");
list.add("bear");
list.add("beaver");
list.add("bison");
randomInt = randomGenerator.nextInt(list.size());
int resourceId = getResources().getIdentifier(list.get(randomInt), "drawable", getPackageName());
b1.setBackgroundResource(resourceId);
I have this code
Random x = new Random(44);
int l = x.nextInt();
int path = R.raw.l;
I know it doesn't work that way,but it explains my situation the most.
i.e. Providing l==5, i want to use R.raw.5 as the path. however, R.raw seems to understand only straightforward values, not the referred ones.
Please help!
You can get int indentifier from your activity with this code:
Random x = new Random(44);
int l = x.nextInt();
int path = getResources().getIdentifier(String.valueOf(l), "raw", getPackageName());
More info in documentation: http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29
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.
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.
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