Pablo Villar
Pablo Villar

Reputation: 167

Obtaining an array element based on a random value

Suppose we have an array of 100 Strings, which you get them from R.string.xml.

private String lapi[]={"R.string.lapi0", "R.string.lapi1", "R.string.lapi2", "R.string.lapi3"..."R.string.lapi99};

Also we have a TextView and a Button:

pelicula=(TextView)findViewById(R.id.lapicera);
btnElegir=(Button)findViewById(R.id.btnElegir);

and we want that when we click the button get us a random value between 0 and 100:

int random=(int) Math.round(Math.random()*100);

The problem: what would be the easiest way to edit the TextView with the array value to which the random value belongs ?. What I want to do is something like this:

pelicula.setText(getResources().getString(lapi[random]));

That is the most effective solution I thought, but doesn't work.

Do you know if there are other similar work as this way ?, without having to use a switch.

Sorry if my english isn't clear.

Thanks in advance!

Upvotes: 0

Views: 33

Answers (1)

Alexis C.
Alexis C.

Reputation: 93842

getString() expects the resource id, you are just giving a String (even if it "corresponds" to the same textual id, it's just a String).

What you want to achieve can be done using getIdentifier() (and you don't even need the array):

Random r = new Random();
...
int randomId = r.nextInt(100);
int resID = getResources().getIdentifier("lapi"+randomId, "string", getPackageName());
pelicula.setText(resID);

Be aware that it's more efficient to retrieve the resource with the id, as the doc states:

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

Upvotes: 2

Related Questions