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?
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,
the implementation of
getJson()does the following,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(),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.