Vamsi Challa
Vamsi Challa

Reputation: 11109

How to access values from "strings.xml" dynamically in android?

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

Upvotes: 2

Views: 14591

Answers (7)

Kirguduck
Kirguduck

Reputation: 796

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);

Upvotes: 0

user3450236
user3450236

Reputation: 243

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.

Upvotes: 0

PC.
PC.

Reputation: 7024

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.

Upvotes: 4

coderz
coderz

Reputation: 1366

You can use this code:

getText(R.string.A);

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

Upvotes: -1

Matthieu
Matthieu

Reputation: 16397

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

Upvotes: -1

chRyNaN
chRyNaN

Reputation: 3692

Try this:

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

Check out the link here.

Upvotes: -1

Marcin S.
Marcin S.

Reputation: 11191

You need to use getResources() method:

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

Upvotes: 2

Related Questions