Home » Android » android – get string from Strings.xml by a variable

android – get string from Strings.xml by a variable

Posted by: admin June 15, 2020 Leave a comment

Questions:

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

How to&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
}

Answer:

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);

Answer:

You wouldn’t. You use strings.xml for constant strings. What you want to do is one of two things.

1)You want a String to be constant, but one of a few options (for example, one item in a list of countries). In this case, put all of the options in strings.xml, and hold which one you’re currently using in an int. When you need to get the actual string, use getString().

2)It really can be any string (for example, a user entered name). In that case it doesn’t go in strings.xml at all, you just use a String variable.

Answer:

This can not be done, resources are converted to unique ints in R.java, and those are used to look up your actual string resources.

So R.string.title is actually something like 0x78E84A34.

You can write your own class which manages strings for you utilizing a HashMap<String,String> to lookup full strings for shorter “key” strings.