K K
K K

Reputation: 101

Best Practice to locally cache web service responses

I am populating an infinite list view with data from a webservice. The data is obtained as a response to POST requests made from the app. What is the best practice to cache such data so that a network call is not made every time the user just scrolls up and down the list? Thank you!

Upvotes: 1

Views: 1987

Answers (3)

Vahid Ghadiri
Vahid Ghadiri

Reputation: 4076

Try Picasso. Another powerful library for image downloading and caching from square. It does everything about caching for you. But if you are still consisting of using LruCache, consider to allocate a special amount of memory for your app. Otherwise your app will cause memory hit.

Upvotes: 0

enl8enmentnow
enl8enmentnow

Reputation: 943

To do this in the past, I have added a cache scheme at network request layer to make the cache transparent to the API caller. The cache expires every x minutes. The cache is persisted using SharedPreferences so that it is available when the app restarts. For example, the API call might be:

List<Item> items = server.getListItems(int page);

Inside getListItems() you check the cache to see if there is a valid cache. If so you return the items in the cache, otherwise you make the network call.

Actually the API was a little more complicated because it supported returning an expired cache immediately, and then doing the network call and updating when the new results came back:

server.getListItems(int page, new ResultListener<List<Item>>() {
    public void onResult(List<Item> items) {
        ...
    }
});

In this scheme, when the cache expired onResult() would be called twice--once with the expired cache and once with the new results.

Good luck!

Upvotes: 0

Nick Davis
Nick Davis

Reputation: 204

Check out the LruCache class, or better yet check out the Android Volley framework developed by Google.

Upvotes: 3

Related Questions