如何正确使用com.octo.android.robospice来缓存位图

时间:2013-11-15 17:51:22

标签: android caching bitmap robospice

我正在使用此处找到的示例:   https://github.com/octo-online/robospice/wiki/Starter-Guide

并尝试扩展它以通过缓存支持位图请求。在LogCat设置为verbose的情况下,我看到日志消息指示位图已成功放入缓存中,但尝试在后续调用中从缓存中读取位图失败,并显示以下日志消息:

11-15 09:14:02.694:D // RequestRunner.java:102(5462):com.octo.android.robospice.persistence.exception.CacheLoadingException:org.codehaus.jackson.map.JsonMappingException :找不到类型[simple type,class android.graphics.Bitmap]的合适构造函数:无法从JSON对象实例化(需要添加/启用类型信息?)

以下是JsonSpiceFactory中的相关代码:

@Override
public CacheManager createCacheManager(Application application) {
    CacheManager cacheManager = new CacheManager();
    try {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;
        JacksonObjectPersisterFactory jacksonObjectPersisterFactory = new JacksonObjectPersisterFactory(application);
        cacheManager.addPersister( jacksonObjectPersisterFactory );

        // Try to add support for bitmap caching here
        InFileBitmapObjectPersister filePersister = new InFileBitmapObjectPersister(application);
        LruCacheBitmapObjectPersister memoryPersister = new LruCacheBitmapObjectPersister(filePersister, cacheSize);
        cacheManager.addPersister(memoryPersister);

    } catch (CacheCreationException e) {
        e.printStackTrace();
    }
    return cacheManager;
}

这是调用spiceManager调用从缓存或网络加载图像的代码:

public void getNetworkBitmap(String url, String cacheKey, GetBitmapListener listener) {

    GetMerchantLogoRequest request = new GetMerchantLogoRequest(url);
    spiceManager.execute(request, cacheKey, DurationInMillis.ONE_HOUR, new NetworkBitmapRequestListener(listener));
}

private class NetworkBitmapRequestListener implements RequestListener<Bitmap> {
    private GetBitmapListener listener;

    public NetworkBitmapRequestListener(GetBitmapListener listener) {
        this.listener = listener;
    }

    @Override
    public void onRequestFailure(SpiceException spiceException) {
        listener.onImageRequestFailure(spiceException);
    }

    @Override
    public void onRequestSuccess(Bitmap logo) {
        listener.onImageRequestSuccess(logo);
    }
}

我是否需要工厂从缓存数据中重建位图?由于这不是Json对象,我需要做些什么才能纠正使用Jackson Json映射的尝试?如果我添加/启用类型信息,杰克逊会做正确的事吗?我该怎么做?

感谢您阅读此内容!

-Eric

2 个答案:

答案 0 :(得分:2)

我通过CacheManager(下面的链接)找到了答案并且偶然发现了“所有元素[persisters] ......按顺序被质疑”所以我重新排序了CreateCacheManager方法中的条目,现在它正在工作。

http://grepcode.com/file/repo1.maven.org/maven2/com.octo.android.robospice/robospice-cache/1.3.1/com/octo/android/robospice/persistence/CacheManager.java

答案 1 :(得分:0)