Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Volley gets results from cache or over network

How can I check whether Volley gets the results of a JsonObjectRequest from the cache or from the network?

I need to show a progress dialog when it needs a network connection but not when the results are quickly received from the cache.

my request looks something like this

volleyQueue = Volley.newRequestQueue(this);
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>(){...stuff}, new Response.ErrorListener(){...errorstuff});
jr.setShouldCache(true);
volleyQueue.add(jr);
like image 564
dumazy Avatar asked Nov 14 '13 08:11

dumazy


People also ask

Is volley deprecated?

GitHub - mcxiaoke/android-volley: DEPRECATED.

What is requestQueue in volley?

requestQueue is used to stack your request and handles your cache. You need to create this RequestQueue in your application class or in a Singleton class. Then only you can use the same requestQueue from multiple activities.

What is volley dependency?

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available on GitHub. Volley offers the following benefits: Automatic scheduling of network requests. Multiple concurrent network connections.


2 Answers

I did this by overriding Request#addMarker and checking for a "cache-hit" marker being added:

public class MyRequest<T> extends Request<T> {

    protected boolean cacheHit;

    @Override
    public void addMarker(String tag) {
        super.addMarker(tag);
        cacheHit = false;
        if (tag.equals("cache-hit")){
            cacheHit = true;
        }
    }
}
like image 121
tkelly Avatar answered Oct 26 '22 04:10

tkelly


Before making the Request you can get the cache from the Request Queue and check if the Entry is not null.

mRequestQueue.getCache().get("key");

The key for each request is usually the URL. I guess you should have to check if the Entry has expired too.

like image 44
Emanuel Canha Avatar answered Oct 26 '22 04:10

Emanuel Canha