Android: How do I get string from resources using its name?
android, resources, string
Solution
The link you are referring to seems to work with strings generated at runtime. The strings from strings.xml are not created at runtime. You can get them via
String mystring = getResources().getString(R.string.mystring);
`getResources()` is a method of the `Context` class. If you are inside a `Activity` or a `Service` (which extend Context) you can use it like in this snippet.
Also note that the whole language dependency can be taken care of by the android framework. Simply create different folders for each language. If english is your default language, just put the english strings into `res/values/strings.xml`. Then create a new folder `values-ru` and put the russian strings with identical names into `res/values-ru/strings.xml`. From this point on android selects the correct one depending on the device locale for you, either when you call `getString()` or when referencing strings in XML via `@string/mystring`. The ones from `res/values/strings.xml` are the fallback ones, if you don't have a folder covering the users locale, this one will be used as default values.
See Localization and Providing Resources for more information.
Problem
I would like to have 2 languages for the UI and separate string values for them in my resource file `res\values\strings.xml`: ``` <string name="tab_Books_en">Books</string> <string name="tab_Quotes_en">Quotes</string> <string name="tab_Questions_en">Questions</string> <string name="tab_Notes_en">Notes</string> <string name="tab_Bookmarks_en">Bookmarks</string> <string name="tab_Books_ru">Книги</string> <string name="tab_Quotes_ru">Цитаты</string> <string name="tab_Questions_ru">Вопросы</string> <string name="tab_Notes_ru">Заметки</string> <string name="tab_Bookmarks_ru">Закладки</string> ``` Now I need to retrieve these values dynamically in my app: ``` spec.setContent(R.id.tabPage1); String pack = getPackageName(); String id = "tab_Books_" + Central.lang; int i = Central.Res.getIdentifier(id, "string", pack); String str = Central.Res.getString(i); ``` My problem is that `i = 0`. Why does not it work in my case?