getDrawable() 在尝试从 imageview 获取位图时给出空对象 [英] getDrawable() gives null object while trying to get bitmap from imageview

查看:32
本文介绍了getDrawable() 在尝试从 imageview 获取位图时给出空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 imageview 使用 glide,我想从该 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();

但它给了

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

帮帮我.

推荐答案

Glide 会异步加载图像,因此您在位图上的测试,在启动加载操作后将返回 null,因为图像尚未加载.

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.

要知道你的图片什么时候确实被加载了,你可以在你的 Glide 请求中设置一个监听器,例如:

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

这篇关于getDrawable() 在尝试从 imageview 获取位图时给出空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆