I'm trying to create and use a cache for a server JSON response.
For example:
cache JSON objects to internal memory and use that when we don't have an internet connection.
In the following sample code, I can not find any document about how to cache it with Volley
and reuse that when server header for update again don't expire.
Like this: set expiration to header and use cache and try to load again after expiration.
I'm trying to set cache mechanism for this method:
private void makeJsonArryReq() {
JsonArrayRequest req = new JsonArrayRequest(Const.URL_JSON_ARRAY,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
msgResponse.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(req,tag_json_arry);
}
Cache method:
public static Cache.Entry parseIgnoreCacheHeaders(NetworkResponse response) {
long now = System.currentTimeMillis();
Map<String, String> headers = response.headers;
long serverDate = 0;
String serverEtag = null;
String headerValue;
headerValue = headers.get("Date");
if (headerValue != null) {
serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
serverEtag = headers.get("ETag");
final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
final long softExpire = now + cacheHitButRefreshed;
final long ttl = now + cacheExpired;
Cache.Entry entry = new Cache.Entry();
entry.data = response.data;
entry.etag = serverEtag;
entry.softTtl = softExpire;
entry.ttl = ttl;
entry.serverDate = serverDate;
entry.responseHeaders = headers;
return entry;
}
Please note that if the web service supports caching output, you don't have to use
CacheRequest
below, becauseVolley
will automatically cache.For your issue, I use some codes inside
parseCacheHeaders
(and refering to @oleksandr_yefremov's codes). The following code I have tested. Of course, can use forJsonArrayRequest
also. Hope this help!UPDATE:
If you want a base class, refer to the following codes:
Then in MainActivity, you can call like this
UPDATE WITH FULL SOURCE CODE:
MainActivity.java:
Manifest file:
Layout file:
If the response is taking from server using String Request then just Replace the Line
with this
It works in my case. Try in your own code.