Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the volley cache automatically?

I want to clear the request queue each 30 minutes for example.

So What is the best way to clear volley cache automatically?

Override methods by extending the volley cache class?

Or build a timer which will clear the cache every times i need?

like image 857
JohnnyBeGoody Avatar asked Jun 28 '14 07:06

JohnnyBeGoody


2 Answers

Google Volley provides 2 ways to clear an item from the Cache:

AppController.getInstance().getRequestQueue().getCache().remove(key);

and

AppController.getInstance().getRequestQueue().getCache().invalidate(key, fullExpire);

Remove means you are removing the actual cached data.

Invalidate means you are just marking the data as invalid. So volley will check with the server whether the data is still valid. The full expire determines whether to use the data before volley has validated it with the server.

To clear cache in each 30 minutes use below code:-

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

So in your code use getMinutesDifference 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, true);
}

It will invalidate the cache,if previous url response >=30 minutes.

like image 84
Giru Bhai Avatar answered Nov 13 '22 23:11

Giru Bhai


Easy way to do that is override onRequestFinished method and clear cache. Or you can run inside the timer after 30 min.

final RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);

requestQueue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<Object>() {
            @Override
            public void onRequestFinished(Request<Object> request) {
                requestQueue.getCache().clear();
            }
        });
like image 27
Dinith Rukshan Kumara Avatar answered Nov 13 '22 23:11

Dinith Rukshan Kumara