How do I check to see if a resource exists in Android
Is there a built in way to check to see if a resource exists or am I left doing something like the following:
boolean result;
int test = mContext.getResources().getIdentifier("my_resource_name", "drawable", mContext.getPackageName());
result = test != 0;
According to the javadoc you don't need the try catch: http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29
if getIdentifier()
returns zero, it means that no such resource exists.
Also 0 - is an illegal resource id.
So your result boolean variable is equivalent to (test != 0)
.
Anyway your try/finally is bad, because all it does it set the result variable to false even if exception is thrown from the body of try: mContext.get.....
and then it just "rethrows" the exception after getting out of finally clause. And I suppose that is not what you want to do in case of exception.
The try/catch block in your code is totally useless (and wrong), since neither getResources()
nor getIdentifier(...)
throw an Exception.
So, getIdentifier(...)
will already return you all you need. Indeed, if it will return 0, then the resource you are looking for does not exist. Otherwise, it will return the associated resource identifier ("0 is not a valid resource ID", indeed).
Here the correct code:
int checkExistence = mContext.getResources().getIdentifier("my_resource_name", "drawable", mContext.getPackageName());
if ( checkExistence != 0 ) { // the resource exists...
result = true;
}
else { // checkExistence == 0 // the resource does NOT exist!!
result = false;
}
i like to do something like that:
public static boolean isResource(Context context, int resId){
if (context != null){
try {
return context.getResources().getResourceName(resId) != null;
} catch (Resources.NotFoundException ignore) {
}
}
return false;
}
so now it's not only for drawable
In case someone is wondering, the "my_resource_name"
in
int checkExistence = mContext.getResources().getIdentifier("my_resource_name", "drawable", mContext.getPackageName());
is actually
String resourceName = String.valueOf(R.drawable.my_resource_name);
int checkExistence = mContext.getResources().getIdentifier(resourceName , "drawable", mContext.getPackageName());