Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 269
Mayank Jindal Avatar asked Dec 13 '15 14:12

Mayank Jindal


1 Answers

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);
like image 52
mrlem Avatar answered Oct 04 '22 23:10

mrlem