2

In Android, to access a string from the strings.xml file, we use R.string.string_id. Would it be possible to have a method such that we'll use the string form of string_id? I mean can we for example have a method GetString("string_id") to retrieve R.string.string_id?

2 Answers 2

4
//Replace this with appropriate context
String name = "name_of_your_string_in_strings_xml_file_goes_here";
int resId = this.getResources().getIdentifier(name, "string", this.getPackageName());
String string = this.getResources().getString(resId);
Sign up to request clarification or add additional context in comments.

1 Comment

Ehrmegerd. We've been trying to do this, but we've been using the string datatype and not the class. Ehrmegerd. Thanks.
-1

It is possible. You have to understand the fact that any data that is pinned to xml files in android are considered as resource to the app. And android resource can be accessed only by means of unique id we provide to them. These ids that are generated are of type int and hence we need to pass a int parameter to get a reference to these resource at run time.

But it is not that only the default way to access them is by using their res value but instead if you could know the name of the string key you could find the id from there and then use the int id to do this.

2 Comments

Is it possible to instead get the int ID from a string form of the ID?
@AndroSelva. There is, actually. Check my answer if you're not aware of this method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.