Never confuse education with intelligence, you can have a PhD and still be an idiot.
- Richard Feynman -

Android:Caching objects

From Juneday education
Jump to: navigation, search


We've been dealing with different strtegies for storing data that should live and be valid as long as the app is installed. Examples of this could be:

  • user settings (typically stored using SharedPreferences)
  • user added data (typically stored in a database)
  • files such as photos (typically stored in the file system)

But what about data that is downloaded by the app? What if the mobile looses connecticity, should the app stop to work? One solution would be to store all objects downloaded to a database. This could be a bit too cumbersome so we might need a temporary storage - a cache. Let's say you download the departure times for a train from Bolzano to Verona on the coming Monday. This is not something we should store in a database permanently (the data may be invalid in a matter of minutes). How do we go about this?

Let's say we assume that the app will be up and running all the time, then we could simply keep the data (about the departure times the coming Monday) in RAM. But then (in realtity), what if we get a phone call and/or all of a sudden feel like watching (a legally downloaded) movie using VLC. Then your app will face the risk of being swapped out and the data (about departures) wil get lost. Imagine you have no network now. Wouldn't be nice if we had a cache - a means to sore the last objects? Of course it would. Let's cache.

Note:' the method described below is NOT intended for storing data permanently. It is aimed at storing data for a short while typically, a couple of minutes.

Using serialization

By letting your domain class, the ones being subject for caching, implement the Serializable API. Not that the classes instance variable types all need to implement the same API for this to work. If you have a class like the following:

public class Student {
  private String name; 
  private String email; 

then caching using Serializable will work fine since String implements this interface. However if your class looks like this:

public class Student {
  private String name; 
  private Email email; 

and Email is a class you've written or a class you import from an external software module then you must make sure that the Email class implements Serializable.

Serializing objects this way works fine but has a downside. If the class is changed (say you change one of the instance variables) then the serialized file is no longer valid. WIll this be a problem if the cache is valid for some ten minutes? If we erase all caches after an app update (including updated classes) then the caches must be deleted. Do you consider tha latter a problem or something we can live with? Hopefully your answers are "yes" and "yes".

Serialize yourself

There are already good tutorials on this so we will not spend more (wasted) energy in this but rather we would like to point you to two good tutorials:

Serialize using ObjectCache

We've written a small software module, ObjectCache, that easily can use in your Android project to cache objects. It is released under Apache License Version 2.0so all you need to do is mention that you've beein using the ObjectCache module.

A brief user manual is available here: ObjectCache/README and a more Android secific manual here: README-ANDROID

Importing ObjectCache

Following the instructions in README-ANDROID for how to make ObjectCache available for your app.

Import the neeed classes by adding:

import se.juneday.ObjectCache;

Declare the ObjectCache

In Android you declare ObjectCache to cache (one single or many objects) of type Student like this:

  // instance variable
  private ObjectCache<List<Student>> cache;

Initialize and read from the cache

To initialize the cache, typically in onStart, you write:

  protected void onCreate(Bundle savedInstanceState) {

    String fileName = null;
    try {
      fileName = AndroidObjectCacheHelper.objectCacheFileName(this, Student.class);
    } catch (AndroidObjectCacheHelperException e) {
    cache = new ObjectCache<>(fileName);
    students = cache.readObjects();
    Log.d(LOG_TAG, "cache:  reading objects: " + students.size());

Store objects in the cache

To store elements in the cache you write, assuming you have the students to store in the Collection reference variable students:

   // ObjectCache
   Log.d(LOG_TAG, "cache: Storing objects: " + students.size()a);

Clear the cache

To clear the cache you write: cache.clear().