How to convert String to your resource identifier (Android Studio)
You cannot get an 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 String resource name e.g. resource_150
<string name="resource_150">150</string>
Now here resource_ is common to your string entries in string.xml , so in your code,
String value = "150"; int resourceId = this.getResources(). getIdentifier("resource_"+value, "string", this.getPackageName()); Now the value of resourceId equivalent to the value of R.string.resource_150
Just make sure this here represents your application context. In your case, MainActivity.this will work.
Resource ID R.string.pokemon_d
I do not believe that you can find a resource identifier by a string value. You can make the value map and resId so that the key is the value, and the value of the map is your res identifier, if you did, you could look at it yourself, but I donβt even know why this would be useful.
I found some tips here: Android, getting a resource id from a string?
Below is an example of how to get strings and their values ββdefined in strings.xml. The only thing you need to do is loop through and check which string holds your value. If you need to repeat this many times, it would 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; } }