Are Android Volley Requests Automatically Cached?
Asked Answered
E

1

2

Ive followed a few tutorials, one in particular shows to do the following if you want to use the cached result for HTTP call.

Cache cache = MyApplication.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(url);
if (entry != null) {
  // means there is a cached result, to use it we have to do something like this...
  new JSONObject(new String(entry.data, "UTF-8"))
} else {
  // no cached result found so make the full request
  JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
                url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        //stuff
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                //stuff
            }
        });

  // Adding request to request queue
  MyApplication.getInstance().addToRequestQueue(jsonObjReq, TAG);}

I was under the impression that the default behaviour was to cache the result, and retrieve the cached result automatically, without having the explicitly get the cached entry - ie. entry = cache.get(url)..

so im basically asking whether or not this is the default behaviour.

thanks

Ebonee answered 27/5, 2014 at 7:20 Comment(2)
Yes,The cache is implemented automatically for your JSON Request.Pardue
thx - thats good to know because these two lines were slowing down my main thread: Cache cache = MyApplication.getInstance().getRequestQueue().getCache(); Cache.Entry entry = cache.get(url);Ebonee
B
17

Yes, Volley caches every response, unless setShouldCache is set to false.

BUT, it does so according to the HTTP cache headers of the response. This means that if there are no cache headers, or they have expired, the JSON response (or any response for that matter) will NOT be cached.

setShouldCache is true by default so you don't have to set it to true manually. It's actually used to explicitly ask for the response not to be cached.

Also, the tutorial you're looking at is wrong. You do not need to manually interact with Volley's cache. Volley does that automatically.

Backset answered 27/5, 2014 at 7:58 Comment(1)
can you answer this #34984802 ?Roughshod

© 2022 - 2024 — McMap. All rights reserved.