androidandroid-resources

Using int value 0 as "null"-equivalent for R.drawable


I'm using an intuitive but perhaps unorthodox shortcut, and I quite simply want to know if it may cause problems, is bad form, or if there is a different, more accepted way of doing it.

The shortcut is: in a function which expects an int which is an R.drawable constant, I sometimes use a 0 to act as an equivalent to passing "null".

Here's a sort of template of how I use this:

int someDrawable = isSomeCondition() ? R.drawable.somedrawable_identifier : 0;
mHandler.post(new UpdateSomeUI(someDrawable));
    
//and, elsewhere in the application,
private class UpdateSomeUI implements Runnable {
   private final int someDrawable;

   public UpdateSomeUI(int someDrawable) {
      this.someDrawable = someDrawable;
   }

   public void run() {
      mSomeImageView.setImageResource(someDrawable);
   }
}

It seems to work - that is, so far it's been doing what I want, and so far I have observed no adverse effects like crashes or the creation of quantum singularities within the device.

Is this safe to do? Is this bad form? I searched for some official integer value that would be recognized as "null" in this sort of circumstance, but came up empty. Does anyone know if such a value exists?


Solution

  • There is no resource that represents "null" and by passing in an invalid resource id, an exception does get thrown and handled internally (when getDrawable(0) is called). The proper thing to do is to only call UpdateSomeUI(someDrawable) when there is actually a valid drawable.

    Something like

    //in a method somewhere: 
    if(isSomeCondition()) {
        mHandler.post(new UpdateSomeUI(R.drawable.somedrawable_identifier));
    }
    

    What's wrong with doing it that way?