Why do they check WeakReference for null?

China☆狼群 提交于 2019-12-12 01:09:16

问题


Here is the blog post on android developers on how download images asynchronously: http://android-developers.blogspot.de/2010/07/multithreading-for-performance.html

The code snippet from it:

class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
    private String url;
    private final WeakReference<ImageView> imageViewReference;

    public BitmapDownloaderTask(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    @Override
    // Actual download method, run in the task thread
    protected Bitmap doInBackground(String... params) {
         // params comes from the execute() call: params[0] is the url.
         return downloadBitmap(params[0]);
    }

    @Override
    // Once the image is downloaded, associates it to the imageView
    protected void onPostExecute(Bitmap bitmap) {
        if (isCancelled()) {
            bitmap = null;
        }

        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }
}

Question: Why do they check imageViewReference for null? Is that an misspell?


回答1:


Looks like really stale code. Remove this check, nothing bad should happen.



来源:https://stackoverflow.com/questions/21336544/why-do-they-check-weakreference-for-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!