Home > Researches, Tutorials, Uncategorized > Caching Objects in Android Internal Storage

Caching Objects in Android Internal Storage

Android provides several options for persisting application data, such as SQLite Databases, SharedPreferences, internal and external storage.

In this post we’ll take a look how we can use the internal storage to persist application data. By default, files saved to internal storage are private to the application and they cannot be accessed by other applications. When the application is uninstalled, the files are removed.

To create and write a file to internal storage, openFileInput(); should be used. This opens a private file associated with the Context’s application package for writing. If the file does not already exits, then it is first created.

openFileInput() returns a FileInputStream, and we could use its write() method, which accepts a byte array as argument, to write the data. However, in the below example we will wrap the FileInputStream into an ObjectOutputStream which provides 2 convenient methodsĀ  for writing and reading objects: writeObject() and readObject().

So, letsĀ  pretend that we need to save a List of some objects. The model class of our object looks like this:

public class Entry implements Serializable{
   private String name;

   public Entry(String name) {
      this.name = name;
   }

   public String getName() {
      return name;
   }
}

Make sure that the model class implements Serializable, otherwise you may get a java.io.NotSerializableException when attempting to write the object on internal storage.

Below is the utility class that provides 2 methods, one for storing objects to internal storage, and another for retrieving objects from internal storage.

public final class InternalStorage{

   private InternalStorage() {}

   public static void writeObject(Context context, String key, Object object) throws IOException {
      FileOutputStream fos = context.openFileOutput(key, Context.MODE_PRIVATE);
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(object);
      oos.close();
      fos.close();
   }

   public static Object readObject(Context context, String key) throws IOException,
         ClassNotFoundException {
      FileInputStream fis = context.openFileInput(key);
      ObjectInputStream ois = new ObjectInputStream(fis);
      Object object = ois.readObject();
      return object;
   }
}

An this is how InternalStorage class can be used to persist and retrieve data from internal storage.

// The list that should be saved to internal storage.
List<Entry> entries = new ArrayList<Entry>();
entries.add(new Entry("House"));
entries.add(new Entry("Car"));
entries.add(new Entry("Job"));

try {
   // Save the list of entries to internal storage
   InternalStorage.writeObject(this, KEY, entries);

   // Retrieve the list from internal storage
   List<Entry> cachedEntries = (List<Entry>) InternalStorage.readObject(this, KEY);

   // Display the items from the list retrieved.
   for (Entry entry : cachedEntries) {
     Log.d(TAG, entry.getName());
   }
} catch (IOException e) {
   Log.e(TAG, e.getMessage());
} catch (ClassNotFoundException e) {
   Log.e(TAG, e.getMessage());
}

 

About these ads
  1. anonymous
    May 15, 2013 at 7:50 am | #1

    Forgive my ignorance, but is there any way that files saved to internal storage can persist even after the app is uninstalled? For example, if you think that data will be needed if the user reinstalls the app…

    • June 1, 2013 at 7:18 pm | #2

      In this case do not save the files on internal storage, save them on external storage.

  2. MrSuS
    July 2, 2013 at 1:51 pm | #3

    How to delete the object from internal storage. Plz need help.

  3. September 28, 2013 at 5:13 pm | #4

    What is key here ? What is the File Type in which the objects are stored.?

    • September 28, 2013 at 5:32 pm | #5

      They KEY could be any string, just make sure you use the same key for writing/reading the file. The file type is irrelevant here, it could have no file extension at all, but that is not important in this case.

  4. December 26, 2013 at 6:15 pm | #6

    Is there a way to set expiration on the cached object?

    • January 8, 2014 at 7:08 am | #7

      One idea would be to add one more field to the cached object that will store the time when the object was created. Then every time on application startup retrieve the cached objects and compare each against an expiration interval, if the allowed cached time expired, delete the object.

  5. thae
    February 25, 2014 at 8:02 am | #8

    can u provide download link?

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 484 other followers

%d bloggers like this: