Get string from Strings.xml variable

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

eg:

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

on the third line: title is a String, and there is no header named String in Strings.xml How can I do this? Please help me

+7
source share
4 answers

As far as I can tell, you can use public int getIdentifier (String name, String defType, String defPackage) . However, its use is not recommended.

To use it (I have not done it yet, but once read about this method), you will probably need:

 int identifier = getResources().getIdentifier ("title","string","your.package.name.here"); if (identifier!=0){ s=getResources().getString(identifier); } else{ s="";//or null or whatever } 
+9
source

One thing you could do to get strings from dynamic keys is to 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 captions from a dynamic key:

 titles.get(titleFromSomewhere); 
+3
source

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

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

2) This can be any string (for example, the username entered by the user). In this case, it is not in the strings.xml file at all, you just use the String variable.

+1
source

This is impossible to do, resources are converted to unique ints in R.java, and they are used to find your real string resources.

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

You can write your own class that manages strings for you, using HashMap<String,String> to search for complete strings for shorter "key" strings.

0
source

All Articles