views:

112

answers:

2

I have an app fetch data from internet, for better performance and bandwidth, I need to implement a cache layer.

There are two different data coming from the internet, one is changing every one hour and another one does not change basically. So for the first type of data, I need to implement an expire policy to make it self deleted after it was created for 1 hour, and when user request that data, I will check the storage first and then goto internet if nothing found.

I thought about using a SharedPrefrence or SQLDatabase to store the json data or serialized object string.

My question is:

1) What should I use, SharedPrefrence or SQLDatabase or anything else, a piece of data is not big but there are maybe many instances of that data.

2) How to implement that expire system.

+2  A: 

I'd use SQLite for storage + have a last invalidated timestamp in Application subclass.
It would get compared against System.currentTimeMillis() on each data access call to decide whether a new set should be fetched. Have a thin proxy layer for that.

alex
A: 

You can use the HTTP HEAD method to check the modification date on the server and see if you really need to fetch new data. Every time the application launches, and at intervals while it is running, query the server to see if the data has changed. This assumes the data is cached on the server and not dynamically generated at every request or dependent on which client makes the request.

Thus you need to store the data and date for each item. SharedPreferences should suffice if the data is a string of moderate length and there is less that a few kilobytes total. If there is a known upper bound on the length of the data then use a database, otherwise you could use plain files. SharedPreferences writes an xml file every time you commit.

You can create a Thread with a long sleep interval to do the periodic checks, or create a Handler and use postDelayed or similar to spawn a checking thread. Check items as often as your maximum for stale data. If you check every 10 minutes, you allow up to 10 minute old data, with an average of half that. Checking at launch will make things appear up to date in most cases anyway.

If all the items expire at once, then you only need to check the date of one item to know they should all be refreshed. If not, you could try to use conditional GET instead of checking the HEAD of each item.

drawnonward
I'd try to avoid HTTP calls as long as possible.
alex
Once you decide you are going to hit the server anyway, you can still save some bandwidth by seeing if the data has actually changed.
drawnonward