Reputation: 3331
I am trying to use an xml resource file to store the mappings of certain values. Then, in my app, when i want to get their values, i would like a way to just access the values in the xml file by key. The problem is that I dont know the key beforehand. There is some logic that evaluates what key to get and then i have to get that key's value. For example:
switch(id) {
case 0:
key = hello;
break;
case 1:
key = world;
break;
}
Now i would like to access the value for these keys that i have stored in an xml file. How can i accomplish this? I dont want to use the SharedPreferences and i cant exactly use resources.getString(R.string. _ ) because i dont know the key beforehand.
Upvotes: 3
Views: 4210
Reputation: 8312
Just use the R.id. within the switch, for example:
public String getStringById(id) {
switch(id) {
case 0:
return getString(R.id.hello); break;
case 1:
return getString(R.id.world); break;
}
}
But if you can't do it like that you could get the int
id for the String like so:
int text_id = YourActivity.this.getResources()
.getIdentifier("hello", "string", YourActivity.this.getPackageName());
So your code will now be like this:
String key = "";
switch(id) {
case 0:
key = hello;
break;
case 1:
key = world;
break;
}
int text_id = YourActivity.this.getResources()
.getIdentifier(key, "string", YourActivity.this.getPackageName());
String text = YourActivity.this.getResources()
.getString(text_id);
return text;
Upvotes: 4
Reputation: 795
if i understood correctly, you only have a String "key" to get the resources?
getResources().getString(
getResources().getIdentifier(key, "string", getPackageName()))
Upvotes: 2