nameishard 2017-10-11 11:42 采纳率: 50%
浏览 948
已采纳

Android图片内存缓存的问题,从LruCache中得到的图片是一张黑的图片

今天自己动手写一个图片加载器,在使用内存缓存时,从LruCache中得到的图片是一张黑的图片,而不是我存储进去的图片。

内存缓存的代码:

     public class MemoryCache implements BaseCacheInterface {
    final LruCache<String, Bitmap> mMemoryCache;

    public MemoryCache() {
        int memorySize = (int) (Runtime.getRuntime().maxMemory() / 1024);
        int cacheSize = memorySize / 8;
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getHeight() / 1024;
            }
        };
    }

        //存
    @Override
    public void add(String imageUrl, Bitmap bmp) {
        Log.d("Http", "Memory cache add");
        mMemoryCache.put(StringUtils.toHex(imageUrl), bmp) ;
    }

        //取
    @Override
    public Bitmap get(String imageUrl) {
        Log.d("Http", "Memory cache get");
        return mMemoryCache.get(StringUtils.toHex(imageUrl));
    }
    }

加载器中,从缓存中读取图片的代码:

     //调用load加载图片到imageview
    public void load(final String link, final ImageView imageView){
        Log.d("Http", "load");

        Bitmap bitmap = mCache.get(link);   //从缓存里获取图片
        if (bitmap != null){
            imageView.setImageBitmap(mCache.get(link));
        } else {
            downloadBitmap(link, imageView);    //缓存里没有,则从网络下载
        }
        Log.d("Http", "over");

    }

    private void downloadBitmap(final String link, final ImageView imageView){
        imageView.setTag(link);
        ImageThreadExecutor.getInstance().execute(new Runnable() {      //封装的线程池
            @Override
            public void run() {
                //imageHttpRequest为封装的Http请求类,downloadToInputStream()返回InputStream
                final Bitmap bitmap = BitmapFactory.decodeStream(imageHttpRequest.downloadToInputStream(link));
                if (imageView.getTag().equals(link) && bitmap != null){
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imageView.setImageBitmap(bitmap);
                        }
                    });
                    mCache.add(link, bitmap);
                }
            }
        });
    }
  • 写回答

1条回答 默认 最新

  • 紫风幻雪 2017-10-12 01:07
    关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog