caching JSON from webservice on android - pattern?
Here's a simply way to do this that doesn't involve a service, threads, alarms, etc. just define a wrapper around your JSON, like,
class MyJson { JSONObject getJson() { ... };}
the implementation of getJson()
does the following,
if (cached json file exists) { if (json file last modified + 1 day > current time) { json = get from network; cache json in file; } else [ json = get from file; }} else { json = get from network; cache json in file;}
in other words, lazy-fetch the fresh json from the network when you need it. this is vastly simpler than periodically updating a cache file by setting alarms and running a service to update the cache ...
from your app, you do the same thing whether it's the first load or the Nth load of the data. you call getJson()
,
new Thread(new Runnable() { public void run() { json = getJson(); // do whatever you need to do after the json is loaded }}).start();
the only downside is that occasionally, the call to get the JSON will take longer, and consequently you must run it in a thread so as not to ANR the UI ... but you should do that anyway, because whether it's in a file or fetched from the network, you should avoid doing IO in the UI thread.