Muhammad Ahmed AbuTalib
Muhammad Ahmed AbuTalib

Reputation: 4302

Weak Reference in async task

I was going through this resource on http://developer.android.com/training/displaying-bitmaps/process-bitmap.html which talks about how to asynchornously sample an image and load it into an image view.

My eye caught the following code

protected void onPostExecute(Bitmap bitmap) {
    if (imageViewReference != null && bitmap != null) {
        final ImageView imageView = imageViewReference.get();
        if (imageView != null) {
            imageView.setImageBitmap(bitmap);
        }
    }
}

The constructor of this asynctask is

  public BitmapWorkerTask(ImageView imageView) {
    // Use a WeakReference to ensure the ImageView can be garbage collected
    imageViewReference = new WeakReference<ImageView>(imageView);
}

What I fail to understand is why does this check exists in onPostExecute

 if (imageViewReference != null && bitmap != null) 

We just initialized the weakreference in the constructor. Why do we have to perform a nullability check on it . ?

This is 100% accurate

if (imageView != null)

We never know if the imageview has being garbage collected or not , however is there any condition which causes the WeakReference class ITSELF to be garbage collected?

Upvotes: 0

Views: 837

Answers (1)

Xaver Kapeller
Xaver Kapeller

Reputation: 49817

Generally I would say no, that can not happen, so it does seem to be redundant, but then again one check does not really hurt performance and can possible prevent some weird crash.

Personally I always declare my WeakReferences as final to be sure.

Upvotes: 2

Related Questions