I couldn't find an updated answer for this. I'm sending requests with Volley to a web API. It returns JSON. I'm using the cache feature like below, but I would like to make sure that the listview is refreshed every so often (say 30 mins for now). How can I invalidate the cache for this given URL to have my app handle that automatically (without a refresh button). This question was helpful in pointing out the difference between invalidate and remove.
MainActivity.java
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONArray(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else
{
// making fresh volley request and getting json
JsonArrayRequest getRequest = new JsonArrayRequest(URL_FEED,
new Response.Listener<JSONArray>()
{
@Override public void onResponse(JSONArray response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
Log.d("Response", response.toString());
}
},......ErrorListener
To refresh listview,you can use volley's serverDate to get the date for when the response was originally received as
AppController.getInstance().getRequestQueue().getCache().get(url).serverDate
this return datetime in long. And in your code use minutedifference function as
public static long getMinutesDifference(long timeStart,long timeStop){
long diff = timeStop - timeStart;
long diffMinutes = diff / (60 * 1000);
return diffMinutes;
}
and Call this function in your code as
Calendar calendar = Calendar.getInstance();
long serverDate = AppController.getInstance().getRequestQueue().getCache().get(url).serverDate;
if(getMinutesDifference(serverDate, calendar.getTimeInMillis()) >=30){
AppController.getInstance().getRequestQueue().getCache().invalidate(URL_FEED, true);
}
It will invalidate the cache,if previous url response >=30 minutes.
This (invalidate) allows to keep using this data until a new call is made and the cached response is overridden with the new response.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With