getDrawable() gives null object while trying to get bitmap from imageview

风格不统一 提交于 2019-12-01 18:03:49

问题


I am using glide for imageview and I want to get bitmap from that imageview--

ImageView imageView = (ImageView) findViewById(R.id.dp);
Glide.with(this).load("http://graph.facebook.com/1615242245409408/picture?type=large").into(imageView);
Bitmap fbbitmap2 = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

But it gives

java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference

Help Me out.


回答1:


Glide loads the image asynchronously, so your test on the bitmap, right after initiating that loading operation will return null, as the image has not yet been loaded.

To know when your image has indeed been loaded, you may set a listener in your Glide request, e.g.:

Glide.with(this)
    .load("http://graph.facebook.com/1615242245409408/picture?type=large")
    .listener(new RequestListener<Uri, GlideDrawable>() {
        @Override
        public boolean onException(Exception e, Uri model, Target<GlideDrawable> target, boolean isFirstResource) {
            return false;
        }

        @Override
        public boolean onResourceReady(GlideDrawable resource, Uri model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
            // drawable is in resource variable
            // if you really need to access the bitmap, you could access it using ((GlideBitmapDrawable) resource).getBitmap()
            return false;
        }
    })
    .into(imageView);


来源:https://stackoverflow.com/questions/34252258/getdrawable-gives-null-object-while-trying-to-get-bitmap-from-imageview

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