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".

Matt
  • 14,906
  • 27
  • 99
  • 149
Vamsi Challa
  • 11,038
  • 31
  • 99
  • 149

7 Answers7

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.

Ghasem
  • 14,455
  • 21
  • 138
  • 171
PC.
  • 6,870
  • 5
  • 36
  • 71
2

You need to use getResources() method:

String a = getResources().getString(R.string.A);
Marcin S.
  • 11,161
  • 6
  • 50
  • 63
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.

user3450236
  • 243
  • 2
  • 7
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);
Kirguduck
  • 748
  • 1
  • 9
  • 20
-1

Try this:

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

Check out the link here.

Community
  • 1
  • 1
chRyNaN
  • 3,592
  • 5
  • 46
  • 74
-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

Matthieu
  • 16,103
  • 10
  • 59
  • 86
  • Ok.. will see this approach as well – Vamsi Challa Nov 19 '12 at 03:31
  • 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). – Matthieu Aug 03 '16 at 23:50
-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.

coderz
  • 1,366
  • 1
  • 12
  • 23