Resources.getIdentifier() has unexpected behavior

2020-07-27 06:32发布

问题:

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?

回答1:

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



回答2:

String resource can contain only strings no special characters no alphabets as tag name.

example

<string name="mydata">Suuuuu</string> is valid

<string name="45645">Suuuuu</string> is invalid

so first check whether your text is valid or not

Use the following code to get it work for you

Code

boolean isValid = (Pattern.matches("[a-zA-Z]+", myText))

if(isValid){
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);
}

}

Thanks Deepak



回答3:

I was banging my head to make this work:

int imgId = getResources().getIdentifier("moviedetails" + movieId , "drawable", getPackageName());
imageview.setImageResource(imgId);

works perfectly fine for me. just needed : "Project --> Clean"