【问题标题】:How can I make work an image cache in Android?如何使工作成为 Android 中的图像缓存?
【发布时间】:2013-03-08 19:31:35
【问题描述】:

我在 android 中缓存图像时遇到了一些麻烦。我正在使用 AsyncTask 从 URL 下载图像。在下载之前,我检查缓存中是否已经包含一个以 URL 为键的 Drawable。如果是,Drawable 将从缓存中取出。

下载由 ListFragment 的自定义 ArrayAdapter 或另一个 Fragment 中的 onCreateView() 触发。

我的问题如下:第一次下载正常。但是,如果我滚动 ListFragment,则会加载错误的图像。如果我重新加载列表或片段,图像将从缓存中获取,ImageViews 将为空。如果我不使用缓存,图像将正确显示。

这里是我的 CacheHandler 的代码:

import android.graphics.drawable.Drawable;
import android.util.LruCache;

public class CacheHandler {
    private static CacheHandler instance;
    private LruCache<String, Drawable> cache;
    private final Logger logger = new Logger(CacheHandler.class);

    private CacheHandler() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;
        cache = new LruCache<String, Drawable>(cacheSize);
    }

    public static CacheHandler getInstance() {
        if (instance == null)
            instance = new CacheHandler();
        return instance;
    }

    public void addToCache(String key, Drawable pic) {
        if (getFromCache(key) == null) {
            cache.put(key, pic);
            logger.debug("Added drawable to cache with key " + key);
        } else
            logger.debug("Drawable with key " + key + " already exists");
    }

    public Drawable getFromCache(String key) {
        logger.debug("Getting image for " + key);
        Drawable d = cache.get(key);
        logger.debug("Image is " + d);
        return d;
    }
}

这里是 AsyncTask 中的调用:

logger.debug("Checking cache");
Drawable d = CacheHandler.getInstance().getFromCache((String) params[0]);

感谢您的帮助。

【问题讨论】:

  • 使用421推荐的库之一,无需重新发明轮子;)

标签: java android caching


【解决方案1】:

您的解决方案有多种方法。 您可以点击以下链接
Link 1

Link 2
Link 3

希望我的回答对您有所帮助。 :)

【讨论】:

    猜你喜欢
    • 2018-10-02
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 2011-02-25
    • 2020-04-27
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    相关资源
    最近更新 更多