user3362035
user3362035

Reputation: 75

Java how to convert string to name of integer

I've got the following problem. I want to write a random generator, which provides me a random image from R.id.drawable ... So I made a random generator and it now it is choosing a random string. But the problem is: I can't draw it, because I have to provide the R.id.drawable.xxxx as an integer variable and not as string. Because this is a name of an integer, I cannot convert it with Integer.Parse(); Is there any solution or does somebody know a way how to choose a random integer? Thanks in advance.

Upvotes: 0

Views: 1217

Answers (4)

Pkmmte
Pkmmte

Reputation: 2868

You can also get the identifier using that string.

For example, to get the integer value of R.drawable.ic_launcher with only the string name of it, you can do this:

getResources().getIdentifier("ic_launcher", "drawable", getPackageName());

Upvotes: 0

Darish
Darish

Reputation: 11481

Consider this example R file.

public static final class id {
    public static final int s1=0x7f050000;
    public static final int s10=0x7f050009;
    public static final int s11=0x7f05000a;
    public static final int s12=0x7f05000b;
    public static final int s13=0x7f05000c;
    public static final int s14=0x7f05000d;
    public static final int s15=0x7f05000e;
    public static final int s16=0x7f05000f;
    public static final int s2=0x7f050001;
    public static final int s3=0x7f050002;
    public static final int s4=0x7f050003;
    public static final int s5=0x7f050004;
    public static final int s6=0x7f050005;
    public static final int s7=0x7f050006;
    public static final int s8=0x7f050007;
    public static final int s9=0x7f050008;
}

Then try to navigate using the following code..

import java.lang.reflect.Field;
/* ... */

 for (int i = 1; i < 16; i++) {
int id = R.id.class.getField("s" + i).getInt(0);
 //do something here
 }

Select one random using your own logic.

refer this question How do I iterate through the id properties of R.java class?

Upvotes: 0

u3l
u3l

Reputation: 3412

Put all of the drawable values in an array drawables. Then generate a random value value between 0 and drawables.length, and access it by drawables[value].

Also, I think you mean:

R.drawable.xxxx

Instead of:

R.id.drawable.xxxx

Upvotes: 3

Code-Apprentice
Code-Apprentice

Reputation: 83527

Note that variable names are only available at compile time, not run-time. This means that you need to find a completely different solution to your problem.

One possibility is a switch statement. Let's say you have 2 images. You can do something like this:

int imageId = -1;
switch(Math.Random(2)) {
    case 1:
        imageId = R.drawable.image1;
        break;

    case 2:
        imageId = R.drawabel.image2;
        break;
}

Upvotes: 0

Related Questions