Kamal
Kamal

Reputation: 5522

Using Reflection with Android

I faced an interesting problem today. I have 4 strings which I need to show on app on random basis. So I simply added the strings to my string.xml and was setting my textview to show the text as

textView.setText(R.string.text_1);

or (if random number was 2)

textView.setText(R.string.text_2);

and so on

I observed that the change is just in last character, so tried using reflection

Class c =  Class.forName("com.startpage.mobile.R$string");

Field field = c.getDeclaredField("text_"+num); //num is 1/2/3/4
System.out.println("********** "+field.get(null));

Now the field.get(null) actually return the Id (hexadecimal number in R.java) value instead of string value I would expect.

Is there a way to fetch actual value of string using reflection or this is something in android which I will have to live with?

Upvotes: 2

Views: 1962

Answers (4)

seanhodges
seanhodges

Reputation: 17524

You can simply request your resource ID from the resource manager:

Class c = Class.forName("com.startpage.mobile.R$string");
Field field = c.getDeclaredField("text_" + num);
int resId = (int)field.get(null);
String text = this.getResources().getString(resId);
textView.setText(text);

Upvotes: 1

Win Myo Htet
Win Myo Htet

Reputation: 5457

R.string.text_2

will always return the hex number. To really get the string value, you have to try the following

MyActivity.this.getResources.getString(R.string.text_2);

Upvotes: 2

Alex Klimashevsky
Alex Klimashevsky

Reputation: 2495

I suggest you to use array of strings and choose random item from it

Upvotes: 0

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43098

getResources.getString(resourceId);

Upvotes: 2

Related Questions