2

App version 2.3.3

Here is what i am looking for...

I have few strings in "values/strings.xml". I wish to retrieve the values depending on the string's "name" attribute and use it my application. The input to which string in the xml should be used comes dynamically. Here is an example...

My input from other file :: "A" => This value changes. It can be any value in A,B,C,D.

I have different strings in strings.xml, like...

    <string name="A">AforApple</string>
<string name="B">BforBall</string>
<string name="C">CforCat</string>
<string name="D">DforDog</string>

Now, how do i programmatically get the value(AforApple) of the String with name="A".

7 Answers 7

4
String str = context.getResources().getString(R.string.A)

or u can use

textBox.setText(R.string.A);

do not forget to import the package com.yourpackackage.R.

Sign up to request clarification or add additional context in comments.

Comments

2

You need to use getResources() method:

String a = getResources().getString(R.string.A);

1 Comment

Sorry, posted before the page updated. Didn't mean to mimic the answer
0

Just for the record, you can also dynamically generate it using reflection.

int stringRes=R.string.class.getField("Here you put the dynamically generated input, such as A").getInt(null);
textView.setText(stringRes);

This will return the resource int value from string XML based on the input, as long as the input value "A" matches string name in the XML, this will retrieve them dynamically.

Comments

0

To access a String resource/value that you’ve defined in an XML file from your Android/Java code, use the Android getString method, like this:

String A = getString(R.string.a_string);

Comments

-1

If your code gets a string like "A" and you are trying to dynamically find the string in your resources that matches that name, I don't think you can do that.

Instead of using the strings.xml, you might want to use arrays.xml and build a HashMap from that before you need to access those strings

2 Comments

Ok.. will see this approach as well
Somebody will need to explain to me all the downvotes... none of the other solutions give any way to dynamically get a string in the XML file from a string in the code (as opposed to an id like R.string.A).
-1

Try this:

    String word = getResources().getString(R.string.A);

Check out the link here.

Comments

-1

You can use this code:

getText(R.string.A);

Basically, you need to pass the resource id as a parameter to the getText() method.

Comments

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.