Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How do I get string from resources using its name?

People also ask

How do you get string from resources?

android:text="@string/hello" /> String string = getString (R. string. hello); You can use either getString(int) or getText(int) to retrieve a string.

Which tells Android to look up a text value from the string resource file?

Let's start with the first part, @string . This is just a way of telling Android to look up a text value from a string resource file. In our case, Android Studio created a string resource file for us called strings.

What is string resource in Android?

A string resource provides text strings for your application with optional text styling and formatting. There are three types of resources that can provide your application with strings: String. XML resource that provides a single string. String Array.

In which folder can you find the string resource file strings xml?

The XML resource files containing localized strings are placed in subfolders of the project's res folder.


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.


Verify if your packageName is correct. You have to refer for the root package of your Android application.

private String getStringResourceByName(String aString) {
      String packageName = getPackageName();
      int resId = getResources().getIdentifier(aString, "string", packageName);
      return getString(resId);
    }

Not from activities only:

public static String getStringByIdName(Context context, String idName) {
    Resources res = context.getResources();
    return res.getString(res.getIdentifier(idName, "string", context.getPackageName()));
}

getResources().getString(getResources().getIdentifier("propertyName", "string", getPackageName()))