getDrawable()在尝试从ImageView获取位图时返回空对象

7

我正在使用Glide加载ImageView中的图片,希望能够从该ImageView中获取Bitmap--

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();

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

请帮我一下。

1个回答

9
Glide能够异步加载图像,因此在启动加载操作后立即对位图进行测试,结果将返回null,因为图像还没有被加载。要知道图像何时确实已加载,您可以在Glide请求中设置一个监听器,例如:
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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接