Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking to see if an ID exists in resources (R.id.something)

Tags:

java

android

So, I have code that's generating ID's for a number of elements using an AtomicInteger that's set by default at Integer.MAX_VALUE and is decremented from there with each view that gets assigned an ID. So the first view with a generated ID would be Integer.MAX_VALUE - 1, the second would be Integer.MAX_VALUE - 2, etc. The problem I'm afraid of is a collision with IDs generated by Android in R.java.

So my question is how can I detect if an ID is already in use and skip it when I'm generating the IDs. I'm only generating at most 30 IDs so this isn't a huge priority nut I'ld like to make this as bug free as possible.

like image 943
Brandon Avatar asked Apr 29 '12 07:04

Brandon


2 Answers

The following code will tell you if the identifier is an id or not.

static final String PACKAGE_ID = "com.your.package.here:id/"
...
...
int id = <your random id here>
String name = getResources().getResourceName(id);
if (name == null || !name.startsWith(PACKAGE_ID)) {
    // id is not an id used by a layout element.
}
like image 176
Jens Avatar answered Sep 23 '22 15:09

Jens


I modified Jens answer from above since, as stated in comments, name will never be null and exception is thrown instead.

private boolean isResourceIdInPackage(String packageName, int resId){
    if(packageName == null || resId == 0){
        return false;
    }

    Resources res = null;
    if(packageName.equals(getPackageName())){
        res = getResources();
    }else{
        try{
            res = getPackageManager().getResourcesForApplication(packageName);
        }catch(PackageManager.NameNotFoundException e){
            Log.w(TAG, packageName + "does not contain " + resId + " ... " + e.getMessage());
        }
    }

    if(res == null){
        return false;
    }

    return isResourceIdInResources(res, resId);
}

private boolean isResourceIdInResources(Resources res, int resId){

    try{            
        getResources().getResourceName(resId);

        //Didn't catch so id is in res
        return true;

    }catch (Resources.NotFoundException e){
        return false;
    }
}
like image 38
Chris Sprague Avatar answered Sep 22 '22 15:09

Chris Sprague