Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R.string; get string from dynamic key name [duplicate]

Possible Duplicate:
Dynamic Resource Loading Android

In Android, I can load a string from the resources with String s = getString(R.string.keyName). But I have a list of categories in my database, each one which has a name. How can I take that category name and then load the appropriate string resource based on it, so that it will work for localization?

Basically, I need to have the keyName be dynamic; my own String variable. Is this possible? Thanks.

like image 264
GendoIkari Avatar asked May 27 '11 21:05

GendoIkari


2 Answers

As your resources cannot be dynamically, you could use a switch statement like:

String name = "";
switch (row.getNameKey()) {
case keyName1:
    name = getString(R.string.keyName1);
    break;
case keyName2:
    name = ...
    ...
}

Another approach woould be the getIdentifier method: http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29

and see: Android: Accessing string.xml using variable name

like image 118
Stuck Avatar answered Nov 14 '22 07:11

Stuck


You can use Java Reflection to turn the string into the resource ID. If you know in advance that it's a string, say R.string.theName, and you have a keyname of "theName", you just need to use reflection on "your.package.com.R.string" (where "your.package.com" is the package name defined in AndroidManifest.xml) to find the class, then use reflection to get the "theName" static member from it. The value you receive can be passed into the getString() method.

like image 25
mah Avatar answered Nov 14 '22 06:11

mah