How to cache and store objects and set an expiration policy in android?

I have an application for retrieving data from the Internet, for better performance and bandwidth I need to implement a cache level.

There are two different data coming from the Internet, each changing every hour, and the other not changing basically. Therefore, for the first data type, I need to implement an expiration policy to make it self-deleted after it has been created within 1 hour, and when the user requests this data, I will first check the store and then go to the Internet if nothing is found.

I was thinking about using SharedPrefrence or SQLDatabase to store json data or a serialized string of an object.

My question is:

1) What to use, SharedPrefrence or SQLDatabase or something else, some of the data is small, but there may be many examples of this data.

2) How to implement this expiration system.

+4
source share
2 answers

I would use SQLite to store +, having a subclass of last invalidated timestamp in Application .
For each data access request, it would be compared with System.currentTimeMillis() to decide whether to retrieve a new set. To do this, you need a thin layer of proxy.

+2
source

You can use the HTTP HEAD method to check the date of the change on the server and see if you really need to receive new data. Each time the application starts and at intervals during its operation, it requests a server to see if the data has changed. This assumes that the data is cached on the server, and not dynamically generated on every request or depending on which client makes the request.

Thus, you need to save the data and date for each item. SharedPreferences should be sufficient if the data is a string of moderate length, and its amount is only a few kilobytes. If there is a known upper bound on the length of the data, then use the database, otherwise you could use simple files. SharedPreferences writes an xml file every time you commit.

You can create a Thread with a long wait interval to perform periodic checks, or create a handler and use postDelayed or the like to create a non-reversible thread. Check items as often as possible for outdated data. If you check every 10 minutes, you get up to 10 minute data, on average half of which. A check at startup will make things appear up to date in most cases anyway.

If all the items expire at once, you only need to check the date of one item to know that they should all be updated. If not, you can try using a conditional GET instead of checking the HEAD of each element.

0
source

Source: https://habr.com/ru/post/1308630/


All Articles