Reputation: 33511
Consider the following code:
protected String getStringResourceByName(String aString) {
String r = null;
if (aString != null) {
String packageName = getPackageName();
int resId = getResources().getIdentifier(aString, "string", packageName);
if (resId == 0) {
r = aString;
} else {
r = getString(resId);
}
}
return r;
}
public void btnOnClick(View view) {
String txt = getStringResourceByName("notexists");
Log.d("test", "notexists: "+txt);
txt = getStringResourceByName("app_name");
Log.d("test", "app_name: "+txt);
txt = getStringResourceByName("12345");
Log.d("test", "12345:"+ txt);
}
Output:
2019-11-14 15:28:59.462 19822-19822/nl.tbwb.rnd.bixolontest D/test: notexists: notexists
2019-11-14 15:28:59.463 19822-19822/nl.tbwb.rnd.bixolontest D/test: app_name: My App Name
...
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x3039
(0x3039 is hexadecimal for 12345)
This crashes on the last call to getStringResourceByName()
, because getResources().getIdentifier()
returns 12345
as resource ID, which doesn't exist.
The documentation doesn't say anything about exceptions. Am I doing something wrong?
Update I know an identifier cannot start with a number, but when using 12345A
as identifier, it does work.
Upvotes: 0
Views: 576
Reputation: 4442
After checking the internal classes, I found something interesting.
ResourcesImpl.java (inside package android.content.res
)
int getIdentifier(String name, String defType, String defPackage) {
if (name == null) {
throw new NullPointerException("name is null");
}
try {
return Integer.parseInt(name);
} catch (Exception e) {
// Ignore
}
return mAssets.getResourceIdentifier(name, defType, defPackage);
}
In this method, it tries to parse the name as Integer first and if it is an Integer, it simply returns the value. But if not, then is check it further down the road.
When you pass an integer(which is not a valid resource name anyway), it simply returns the value, per say. But this resource actually doesn't exist at all! And Boom! that why the crash.
Upvotes: 1