GetDrawable () provides a null object when trying to get a bitmap from an image

I use glide to view images, and I want to get a bitmap from this image -

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 he gives

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

Help me.

+4
source share
1 answer

Glide loads the image asynchronously, so your test on the bitmap immediately after starting this load operation returns null, since the image has not yet been loaded.

To find out when your image is really loaded, you can install a listener in your Glide request, for example:

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);
+5
source

Source: https://habr.com/ru/post/1619716/


All Articles