Using Reflection with Android

Faced an interesting problem today. In my android app I needed to show some random strings on the UI (textview).  So obvious solution was to add the strings in string.xml (for supproting i18n), and then fetch the text based on the random number generated.

textView.setText(R.id.text_1);

or if random number is 2

textView.setText(R.id.text_2);

and so on

I realized that only change happening is the last one digit, so this is a good candidate for using reflections.

Class c =  Class.forName("com.startpage.mobile.R$string");
Field field = c.getDeclaredField("tip_"+tip);
tipTextView.setText(field.get(null)));

But this actually gave an Exception for ClassCast, so I realized that field.get(null) is actually returning the resource Id (as shown in R.java class) instead of string value.

The fix found was to use getResources().getString(resource_id) to fetch the string from the resource id

Class c =  Class.forName("com.startpage.mobile.R$string");
Field field = c.getDeclaredField("tip_"+tip);
tipTextView.setText(getResources().getString((Integer)field.get(null)));