求解惑

我很納悶,爲什麼我用Volley請求StringRequest,存了緩存文件,但是在沒有網絡的情況下卻不能讀出。

首先,我門通過 StringRequest
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
這個方法調用由我們自己訂製的方法 onResponse(),我門在onResponse()中寫入我們對於獲得網絡的數據的處理

@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
}

這個方法用於將網絡返回的抽象的數據類型轉化成我們需要的數據類型,這裏是String類型。

可以看到,無網絡狀態下,文本輸出爲null
而toast的值爲之前的請求:
byte[] data=mySingleton.getRequestQueue().getCache().get(sRequest.getCacheKey()).data;
Toast.makeText(this, new String(data), Toast.LENGTH_LONG).show();
由此可知,在RequestQueue的Cache中有我們所需的緩存。那麼爲什麼我們不能通過文筆顯示呢?
當我們使用byte[] data=sRequest.getCacheEntry().data;時,報出空指針異常,所以sRequest.getCacheEntry()爲空。
所以,在源碼的CacheDispatcher中:
// Attempt to retrieve this item from cache.
Cache.Entry entry = mCache.get(request.getCacheKey());
if (entry == null) {
request.addMarker("cache-miss");
// Cache miss; send off to the network dispatcher.
mNetworkQueue.put(request);
continue;
}

// If it is completely expired, just send it to the network.
if (entry.isExpired()) {
request.addMarker("cache-hit-expired");
request.setCacheEntry(entry);
mNetworkQueue.put(request);
continue;
}
entry不爲空。
Toast.makeText(this, ""+entry.isExpired(), Toast.LENGTH_LONG).show();
true
entry爲失效。
Toast.makeText(this, ""+sRequest.getCacheEntry(), Toast.LENGTH_LONG).show();
null
entry爲空
明明我們可以從entry裏面獲得值的,爲什麼輸出是null?
通過這篇文章的

http://www.cnblogs.com/angeldevil/p/3735051.html

在Request类中有一个方法叫parseNetworkResponse,Request的子类会覆写这个方法解析网络请求的结果,在这个方法中会调用

return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
返回Response<T>,并通过HttpHeaderParse.parseCacheHeaders解析Cache.Entity,即生成缓存对象,在parseaCheHeaders中会根据网络请求结果中的Header中的Expires、Cache-Control等信息判断是否需要缓存,如果不需要就返回null不缓存。

当对请求做了缓存后,没网的情况下也可以得到数据。
我們可以看看位於Request子類的parseNetworkResponse()方法,以StringRequest爲例:

@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}

於是,我們轉換到Response,success()方法:
public static <T> Response<T> success(T result, Cache.Entry cacheEntry) {
return new Response<T>(result, cacheEntry);
}
我們知道它是返回含cacheEntry的方法。那麼HttpHeaderParser.parseCacheHeaders(response)是幹什麼的呢?
因爲代碼過長,直接看這一句:
if (token.equals("no-cache") || token.equals("no-store")) {
return null;
} else if (token.startsWith("max-age=")) {
try {
maxAge = Long.parseLong(token.substring(8));
} catch (Exception e) {
}
我們通過chrome可以看到:根據header來指定緩存的時間。

我傳入的網址cache-control爲no-cache,返回的是null.
但此處是在網路請求過後才會出現的,於是,我們需要進DiskBasedCache和網絡請求看看。
request.shouldCache默認爲true.
if (request.shouldCache() && response.cacheEntry != null) {
mCache.put(request.getCacheKey(), response.cacheEntry);
request.addMarker("network-cache-written");
}
由此可見NetworkDispatcher只是進行網絡請求,並把它的結果傳給下一級,順便,把由各子類封裝的parseNetworkResponse的Response數據的cacheEntry數據存在文件中~
看了這一串,應該還記得我們是爲什麼說這麼多吧?說實話,我往回翻了好多次。
因爲我們在數據中已經存了這個文件,所以直接用cache可以獲得entry,因爲Request的默認爲: private Cache.Entry mCacheEntry = null;

我也是醉了。現在糾結
byte[] data=mySingleton.getRequestQueue().getCache().get(sRequest.getCacheKey()).data;
有值。

// Attempt to retrieve this item from cache.
Cache.Entry entry = mCache.get(request.getCacheKey());
if (entry == null) {
request.addMarker("cache-miss");
// Cache miss; send off to the network dispatcher.
mNetworkQueue.put(request);
continue;
}

// If it is completely expired, just send it to the network.
if (entry.isExpired()) {
request.addMarker("cache-hit-expired");
request.setCacheEntry(entry);

sRequest.getCacheEntry()爲空,問entry爲空還是isExpired.現在 isExpired爲true爲真,按照邏輯,應該在第一個if條件句,entry爲null,但mySingleton.getRequestQueue().getCache().get(sRequest.getCacheKey()).data;有輸出值??

后来部门大神说是操作进行时缓存还没有初始化的问题。对哇。。这是多线程,mark~

另外,关于volley的L1级图片缓存:

When implementing Volley as your image loading solution you will find that, while it does handle L2 caching on its own, it requires but does not include an L1 image cache out of the box.

The Volley ImageCache interface allows you to use your preferred L1 cache implementation. Unfortunately, one of the shortcomings of Volley (and the reason for this article) is that there is no default cache implementation. The I/O presentation shows a code snippet for BitmapLruCache, but the library itself does not include any such implementation. 

链接在此:https://www.captechconsulting.com/blog/raymond-robinson/google-io-2013-volley-image-cache-tutorial

原文地址:https://www.cnblogs.com/Steve-Kale/p/4014672.html