I am using Volley and I want to cache response(no server control-cache headers).
I want to show the cached value only if there is no internet.
What I tried:
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 cachedEvents = cache.get(GetEvents.KEY_EVENTS_CACHE);
if (NetworkChecker.isOnline(mContext)) {
// puts the entry with the new data to the cache
cache.put(GetEvents.KEY_EVENTS_CACHE, cachedEntryForRequest);
// return null so the new data to be shown
cachedEntryForRequest = null;
} else {
// show the cached data if the device is offline
if (cachedEvents != null) {
Log.v(TAG, "cached event is NOT NULL");
cachedEntryForRequest.data = cachedEvents.data;
} else {
Log.v(TAG, "cached event is NULL");
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));
}
}
This is my own solution but I'm doing something wrong because it's showing the cache result even if the device is online?!?!?
0 comments:
Post a Comment