Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check to see if a resource exists in Android

Tags:

java

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;
like image 832
user432209 Avatar asked Dec 27 '10 15:12

user432209


4 Answers

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.

like image 194
m_vitaly Avatar answered Oct 06 '22 17:10

m_vitaly


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;
}
like image 34
Paolo Rovelli Avatar answered Oct 06 '22 17:10

Paolo Rovelli


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

like image 6
JCDecary Avatar answered Oct 06 '22 19:10

JCDecary


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());
like image 5
Bugs Happen Avatar answered Oct 06 '22 17:10

Bugs Happen