我正在使用Volley,我想缓存响应(没有服务器控制缓存头)。
我想仅在没有互联网的情况下显示缓存值。
我尝试了什么:
private Entry getCachedEntry(NetworkResponse response) {
// entry that will be passed to the response instance
Entry cachedEntryForRequest = HttpHeaderParser
.parseIgnoreCacheHeaders(response);
// The request queue cache
Cache cache = BaseApplication.getInstance().getRequestQueue()
.getCache();
// gets the cached entry for the request
Entry cachedItems = cache.get(GetEvents.KEY_CACHE);
if (NetworkChecker.isOnline(mContext)) {
// puts the entry with the new data to the cache
cache.put(GetEvents.KEY_CACHE, cachedEntryForRequest);
// return null so the new data to be shown
cachedEntryForRequest = null;
} else {
// show the cached data if the device is offline
if (cachedItems != null) {
cachedEntryForRequest.data = cachedItems.data;
} else {
cachedEntryForRequest = null;
}
}
return cachedEntryForRequest;
}
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
Log.v(TAG, "response: " + json);
Object fromJson = mGson.fromJson(json, mType);
return Response.success((T) fromJson, getCacheEntry(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
这是我自己的解决方案,但我做错了,因为即使设备在线,它也会显示缓存结果?!?!?