"Descript...">

Android XML resource file reference from variable

I have XML error codes in the following format:

<resources>
    <string name ="e1001">"Description of error 1001"</string>
    <string name ="e1002">"Description of error 1002"</string>
...
</resources>

      

Usually they can be accessed in the usual way, i.e. R.string.e1001

...

Is it possible to reference using a variable in the reference or will I have to use Xpath?

This obviously doesn't work , but something like:

String s = getErrorCode(); //returns a value, i.e "e1001"
showAlert(R.string.+s);

      

+3


source to share


2 answers


Inside Activity

/, Fragment

you can get the value of the String

resource by doing the following:

//Activity
String s = getString(R.string.s);

//Fragment
String s = getActivity().getString(R.string.s);

      

Your problem is not knowing what refunds are R.string.s

actually being returned as int

. Basically, this is the link that Android uses to locate the string in your application.

getString()

method inside the Context class - see the docs for more



EDIT:

As per your comment, you will want to try this:

String resourceName = getErrorCode();
String alert = getResources().getIdentifier(resourceName, "string", getPackageName());
showAlert(alert);

      

0


source


Try this for Activity

String s = getString(R.string.urresourcename);

      



Try this for a snippet

String s = getActivity().getString(R.string.urresourcename);

      

0


source







All Articles