11

I have an xml string in my values/strings.xml file

    <string name="pokemon_d">150</string>

And I have the String "150" in my controller MainActivity.java. In my MainActivity, how can I convert that String to the resource ID of the pokemon_d String in the xml file? Is this even possible?

Viral Patel
  • 32,418
  • 18
  • 82
  • 110
gciluffo
  • 153
  • 1
  • 3
  • 11

3 Answers3

21

You can not get identifier by value, but you can make your identifier name look like a value and get it by string name,

So what I suggest,

use your String resource name something like, resource_150

<string name="resource_150">150</string>

Now here resource_ is common for your string entries in string.xml file, so in your code,

String value = "150";
int resourceId = this.getResources().
             getIdentifier("resource_"+value, "string", this.getPackageName());

Now resourceId value is as equivalent to R.string.resource_150

Just make sure here this represent your application context. In your case MainActivity.this will work.

user370305
  • 108,599
  • 23
  • 164
  • 151
0

I have found some tips here: Android, getting resource ID from string?

Below an example how to get strings and their values defined in strings.xml. The only thing you have to do is making a loop and test which string is holding your value. If you need to repeat this many times it might be better to build an array. //---------

    String strField = "";
    int resourceId = -1;
    String sClassName = getPackageName() + ".R$string";
    try {
        Class classToInvestigate = Class.forName(sClassName); 

        Field fields[] = classToInvestigate.getDeclaredFields();

        strField = fields[0].getName();     
        resourceId = getResourceId(strField,"string",getPackageName());

        String test = getResources().getString(resourceId);

        Toast.makeText(this,
                       "Field: " + strField + " value: " + test ,
                       Toast.LENGTH_SHORT).show();


    } catch (ClassNotFoundException e) {
            Toast.makeText(this,
                       "Class not found" ,
                       Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(this,
                       "Error: " + e.getMessage() ,
                       Toast.LENGTH_SHORT).show();
    }


}
public int getResourceId(String pVariableName, String pResourcename, String pPackageName) 
{
    try {
        return getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}   
Community
  • 1
  • 1
Gerard Frijters
  • 358
  • 3
  • 11
0

In addition to user370305, you could make an extension and use it the same was as with int ids.

import android.app.Activity

fun Activity.getString(id: String): String {
    val resourceId = this.resources.getIdentifier(id, "string", this.packageName)
    return getString(resourceId)
}
ARR
  • 2,074
  • 1
  • 19
  • 28