Thursday, August 19, 2010

Android musings: Options for storing persistent data

Android provides the following options for storing application data:
  • Preferences: Store primitive data in key value pairs (a detailed explanation below)
  • SQLite database: Preferred approach if your application needs relational data. Further, android SDK provides sqlite3 tool, which enables you to manage the SQLite database from a remote shell
  • Internal Storage: Save data in a file directly to device's internal storage. By default this data is private to the application only. When the user uninstalls the specific application, these files are removed
  • External Storage: Save data in a file into a removable media (such as an SD card) or an internal (non-removable storage). NOTE: There is no security enforced on files written to external storage. All applications can read and write to such files. Moreover users can manually (or accidentally) remove such files
For my SMSPost project, I had the specific need of storing two persistent parameters, e.g. frequency of scheduled run and URL for SMS upload.

I chose Shared Preferences as the persistent data storage approach, purely because of the ease of use in handling preferences. Shared preferences, enables relatively static data to be stored as Key Value pair and the data is accessible to all activities and services in the application. (NOTE - You can share your preferences across other application by defining the preference mode as MODE_WORLD_READABLE or MODE_WORLD_WRITABLE. For SMSPost application, we just needed the data to be available within the application, hence we set the mode as MODE PRIVATE) 

Sample Code:

// get handle to the shared preferences (called from an Activity Class)
        preferences = getSharedPreferences(Const.PREFS_NAME, MODE_PRIVATE); 

// writing to shared preferences
       SharedPreferences.Editor editor = preferences.edit();
       editor.putString(Const.PUBLIC_STATIC_TIMEPICKER_IDENTIFIER, resultFrequency);

//Reading from shared preferences
       if (preferences.getString(Const.PUBLIC_STATIC_TIMEPICKER_IDENTIFIER, "") == "")
                        return false;


Please leave a comment if you have used any of the data storage options and would like to share your experiences.

    No comments: