Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get string from Strings.xml by a variable

Tags:

android

i want to get a string from strings.xml. i know how to do this. but my problem is something else: i have a String Variable which changes every time, and every time it changes, i want to look at strings.xml and check if that String variable exists in Strings.xml, then get text.

for example:

String title="sample title" \\ which changes
String city= "sample city"
String s = getResources().getString(R.string.title);

in the third line: title is a String, and there isn't any "title" named String in Strings.xml how can i do this? please help me

like image 441
rezam Avatar asked May 08 '13 18:05

rezam


2 Answers

As far as I can tell, you could use public int getIdentifier (String name, String defType, String defPackage). Its use is discouraged, though.

To use it (I haven't done it but I had once read about the method) you probably would need to:

int identifier = getResources().getIdentifier ("title","string","your.package.name.here");
if (identifier!=0){
     s=getResources().getString(identifier);
}
else{
    s="";//or null or whatever
}
like image 164
DigCamara Avatar answered Sep 24 '22 18:09

DigCamara


One thing you could do to get strings from dynamic keys is make 2 string arrays and put them in a HashMap.

arrays.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="title_keys">
        <item>title1</item>
        <item>title2</item>
        <item>title3</item>
    </string-array>
    <string-array name="title_values">
        <item>Real Title 1</item>
        <item>Real Title 2</item>
        <item>Real Title 3</item>
    </string-array>
</resources>

And in your code:

String[] titleKeys = getResources().getStringArray(R.array.title_keys);
String[] titleValues = getResources().getStringArray(R.array.title_values);

HashMap<String, String> titles = new HashMap<String, String>();

for(int i = 0; i < titleKeys.length; i++) {
    titles.put(titleKeys[i], titleValues[i]);
}

Finally, to get your titles from a dynamic key:

titles.get(titleFromSomewhere);
like image 25
Krauxe Avatar answered Sep 24 '22 18:09

Krauxe