I use Resources.getIdentifier to load up string resources dynamically; because I am dynamically passed a string that needs to be translated from my resources files. It returns 0 when the resource doesn’t exist; so I handle that. However, when I pass in a string that is a numeric; even though I don’t have that defined in my resources, it returns the number I passed in instead of 0. This causes a crash when I try to get that resource.
int identifier = context.getResources().getIdentifier(myText, "string", "com.farragut.android.emsspeak");
if (identifier > 0) {
text2.setVisibility(View.VISIBLE);
text2.setText(context.getResources().getString(identifier));
} else {
text2.setVisibility(View.GONE);
}
Is this defined behavior?? I can’t imagine why it works fine when myText is “BLAH” but then when myText is “12” it is different. The only thing I can think of is to test if myText is numeric first; though the only way I can find to do that is to try to parse it as an integer and catch a numberFormatException. Is that the best solution?
Well this is kinda weird but if I specify the fully qualified name like it’s mentioned in the getIdentifier() documentation it works properly otherwise i got the same result like you.
Try it with
getIdentifier("com.farragut.android.emsspeak:string/"+myText, null, null);