+1 for oleksandr_yefremov and skyfishjy also offers here a specific reusable class suitable for json or other string based APIs:
public class CachingStringRequest extends StringRequest { public CachingStringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) { super(method, url, listener, errorListener); } public CachingStringRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) { super(url, listener, errorListener); } @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, parseIgnoreCacheHeaders(response)); } }
where the parseIgnoreCacheHeaders () function comes from the answer oleksandr_yefremov above. Use the CachingStringRequest class wherever the resulting json can cache for 3 minutes (live) and 24 hours (expired, but still available). Request example:
CachingStringRequest stringRequest = new CachingStringRequest(MY_API_URL, callback);
and inside the onResponse () callback function, parse json. Set any caching restrictions that you want — you can parameterize to add custom expiration per request.
For fun, try this in a simple application that downloads json and displays the downloaded information. After filling the cache with the first successful download, watch for fast rendering when you change orientation while the cache lives (loading does not take into account the hit in real time). Now kill the application, wait 3 minutes until its expiration date (but not 24 hours to remove it from the cache), turn on airplane mode and restart the application. A Volley error callback will be called, and the “successful” response to the onResponse () request will come from cached data, which will allow your application to both display the content and know / warn that it came from the expired cache.
One way to do this caching would be to eliminate boot loaders and other ways of handling orientation changes. If the request goes through Singleton Volley and the results are cached, updates that occur by changing the orientation are quickly displayed from the cache automatically using Volley without Loader.
Of course, this does not meet all the requirements. Ymmv
larham1 Sep 18 '14 at 19:53 2014-09-18 19:53
source share