Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

caching JSON from webservice on android - pattern?

I want to cache data from a json-webservice in my android app. The first time, the application is launched, it should wait until all data was loaded from service. After that initial load the app should check from time to time(some days) if there is new data available. If yes, the locally stored data should be refreshed and loaded the next time the app is started.

Currently I'm trying to solve this by an IntentService and by saving the loaded data in a file - but i isn't a very clean an beautiful way!

Does anybody know a clean way to do this? A caching-pattern?

like image 440
fmo Avatar asked Mar 23 '12 00:03

fmo


1 Answers

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.

like image 100
Jeffrey Blattman Avatar answered Oct 30 '22 00:10

Jeffrey Blattman