Home > Programming / tutorials > Data Storage Mechanisms in Android

Data Storage Mechanisms in Android

January 17th, 2011 Leave a comment Go to comments

In this post we will discuss data storage techniques in android.  Android has three  data storage mechanisms

1)    Preferences

2)    Local Files

3)    SQLite database

By default all files, databases and preferences is restricted to the application that created them. If want to share data with other applications you need to make use of Content Providers. Content Providers is not a storage mechanism they provide well defined interface for sharing private data.


Preferences are light weight mechanisms to store set of values in terms of key-value pairs. E.g. string, array etc. Further preferences are of two types

  1. SharedPreferences: Stores data in terms of key-value pairs and can be accessed by application components working in the same context.

Creating and Saving Shared Preferences:

// select your mode to be either private or public.

int mode= Activity.MODE.PRIVATE;

// get the sharedPreference of your context.

SharedPreferences  mySharedPreferences ; mySharedPreferences=getSharedPreferences(“Name_of_your_preference”,mode);

// retrieve an editor to modify the shared preferences

SharedPreferences.Editor editor= mySharedPreferences.edit();

/* now store your primitive type values. In this case it is true, 1f and Hello! World  */



editor.putString(“myString”,” Hello! World”);

//save the changes that you made


Retrieving Shared Preferences

/* Now we will try to retrieve the data saved i.e. true, 1f and Hello! World */

int mode = Activity.MODE_PRIVATE;

SharedPreferences  mySharedPreferences ; mySharedPreferences=getSharedPreferences(“Name_of_your_preference”,mode);

/ Retrieve the saved values.

boolean mBoolean = mySharedPreferences.getBoolean(“myBoolean”,false);

float mFloat = mySharedPreferences.getFloat(“myFloat”, 0f);

String mSstring;

mString= mySharedPreferences.getString(“myString”,“ ”);

/* Now mBoolean, mFloat, mString will hold the data saved. The values false, 0f and “ “ (space) are the values that are returned when data does not exist or cannot be retrieved*/

  1. onSaveInstanceState: It designed to save the state of your activity when it becomes eligible for termination.

Saving Instance State

/* To save your Activity instance variables override Activity’s onSaveInstanceState event handler and use Bundle parameter to save instance state*/


public void onSaveInstanceState(Bundle  myBundle) {

// Retrieve the View

TextView myTextView = (TextView)findViewById(R.id.myTextView);

String myData= myTextView.getText().toString();

// Save its state

myBundle.putString(“Name_of_my_param ”, myData);

super.onSaveInstanceState(myBundle); }

Restoring Instance State

/* The Bundle that we saved previously will be passed to onRestoreState and onCreate methods. Let’s see how we can extract values from the Bundle*/


public void onCreate(Bundle icicle) {



TextView myTextView = (TextView)findViewById(R.id.myTextView);

String text = “”;

if (icicle != null && icicle.containsKey(“Name_of_my_param ”))

text = icicle.getString(“Name_of_my_param ”);

myTextView.setText(text); }


When you do not want to use Android’s managed mechanisms to store data you can use files directly with standard Java I/O classes and methods.

Reading and Writing a File

String FILE_NAME = “myFile.txt”;

// Create a new output file stream that’s private to this application.

FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);

// Create a new file input stream.

FileInputStream fis = openFileInput(FILE_NAME);

These methods only support files in the current application folder; specifying path separators will cause an exception to be thrown.

If the filename you specify when creating a FileOutputStream does not exist, Android will create it for you. To append an existing file, specify the mode as Context.MODE_APPEND.

Method 3: SQLite DATABASE

Before creating and using SQLite database we need to know few things.

1)    contentValues: These objects are used to insert new rows into the database. Each contentValues object represents a single row.

2)    Cursor: These objects are used for extracting over query results. They act as pointer to the result set from a database query. Cursor provides several functions navigate through your query results like moveToFirst, moveToNext, getCount, getColumnName etc.

3)    Any databases you create will be accessible by name to any class in the application, but not outside the application.

4)    All Android databases are stored in the data/data/<package_name>/databases

folder on your device (or emulator).

5)    Create a helper class to hide complexities of adding, removing and updating data. An extension of the SQLiteOpenHelper class, is used to simplify opening, and creating database.

/* Below code shows how to create a helper class and extend SQLiteOpenHelper.*/

/**Below code snippet is taken from Pro Android Developers*/

import android.content.Context;

import android.database.*;

import android.database.sqlite.*;

import android.database.sqlite.SQLiteDatabase.CursorFactory;

import android.util.Log;

public class MyDBAdapter {

private static final String DATABASE_NAME = “myDatabase.db”;

private static final String DATABASE_TABLE = “mainTable”;

private static final int DATABASE_VERSION = 1;

// The index (key) column name for use in where clauses.

public static final String KEY_ID=”_id”;

// The name and column index of each column in your database.

public static final String KEY_NAME=”name”;

public static final int NAME_COLUMN = 1;

// TODO: Create public field for each column in your table.

// SQL Statement to create a new database.

private static final String DATABASE_CREATE = “create table “ +


“ integer primary key autoincrement, “ +

KEY_NAME + “ text not null);”;

// Variable to hold the database instance

private SQLiteDatabase db;

// Context of the application using the database.

private final Context context;

// Database open/upgrade helper

private myDbHelper dbHelper;

public MyDBAdapter(Context _context) {

context = _context;

dbHelper = new myDbHelper(context, DATABASE_NAME, null,



public MyDBAdapter open() throws SQLException {

db = dbHelper.getWritableDatabase();

return this;


public void close() {



public long insertEntry(MyObject _myObject) {

ContentValues contentValues = new ContentValues();

// TODO fill in ContentValues to represent the new row

return db.insert(DATABASE_TABLE, null, contentValues);


public boolean removeEntry(long _rowIndex) {

return db.delete(DATABASE_TABLE, KEY_ID +

“=” + _rowIndex, null) > 0;


public Cursor getAllEntries () {

return db.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_NAME},

null, null, null, null, null);


public MyObject getEntry(long _rowIndex) {

MyObject objectInstance = new MyObject();

// TODO Return a cursor to a row from the database and

// use the values to populate an instance of MyObject

return objectInstance;


public int updateEntry(long _rowIndex, MyObject _myObject) {

String where = KEY_ID + “=” + _rowIndex;

ContentValues contentValues = new ContentValues();

// TODO fill in the ContentValue based on the new object

return db.update(DATABASE_TABLE, contentValues, where, null);


private static class myDbHelper extends SQLiteOpenHelper {

public myDbHelper(Context context, String name,

CursorFactory factory, int version) {


// Called when no database exists in

// disk and the helper class needs

// to create a new one.


public void onCreate(SQLiteDatabase _db) {



// Called when there is a database version mismatch meaning that

// the version of the database on disk needs to be upgraded to

// the current version.


public void onUpgrade(SQLiteDatabase _db, int _oldVersion,

int _newVersion) {

// Log the version upgrade.

Log.w(“TaskDBAdapter”, “Upgrading from version “ +

_oldVersion + “ to “ +

_newVersion +

“, which will destroy all old data”);

// Upgrade the existing database to conform to the new version.

// Multiple previous versions can be handled by comparing

// _oldVersion and _newVersion values.

// The simplest case is to drop the old table and create a

// new one.


// Create a new one.





Extracting Results from Database

// Return all rows for columns one and three, no duplicates

String[] result_columns = new String[] {KEY_ID, KEY_COL1, KEY_COL3};

Cursor allRows = myDatabase.query(true, DATABASE_TABLE, result_columns,

null, null, null, null, null, null);

// Return all columns for rows where column 3 equals a set value

// and the rows are ordered by column 5.

String where = KEY_COL3 + “=” + requiredValue;

String order = KEY_COL5;

Cursor myResult = myDatabase.query(DATABASE_TABLE, null, where,

null, null, null, order);

Extracting Results from Cursor

/* Below code snippet shows how to extract data from cursor */


Cursor myGold = myDatabase.query(“GoldHoards”, null, null, null, null,

null, null);

float totalHoard = 0f;

// Make sure there is at least one row.

if (myGold.moveToFirst()) {

// Iterate over each cursor.

do {

float hoard = myGold.getFloat(GOLD_HOARDED_COLUMN);

totalHoard += hoard;

} while(myGold.moveToNext());


float averageHoard = totalHoard / myGold.getCount();

Inserting Rows

// Create a new row of values to insert.

ContentValues newValues = new ContentValues();

// Assign values for each row.

newValues.put(COLUMN_NAME, newValue);

[ … Repeat for each column … ]

// Insert the row into your table

myDatabase.insert(DATABASE_TABLE, null, newValues);

Updating Rows

// Define the updated row content.

ContentValues updatedValues = new ContentValues();

// Assign values for each row.

updatedValues.put(COLUMN_NAME, newValue);

[ … Repeat for each column … ]

String where = KEY_ID + “=” + rowId;

// Update the row with the specified index with the new values.

myDatabase.update(DATABASE_TABLE, updatedValues, where, null);

Deleting Rows

myDatabase.delete(DATABASE_TABLE, KEY_ID + “=” + rowId, null);

  1. December 3rd, 2014 at 02:39 | #1

    A good android app must have a capability to store some data, even if only to save information about the app state during onPause() so the users progress is not lost. We have three principle data store options in android:

    1. Saving key-value pair of simple data type in a shared preference file

    2. Saving arbitrary files in Android’s file system

    3. Using database managed by SQLite

    Saving Key value Sets:

    If we have relatively small collection of key-values that we‘d like to save, we should use the SharedPreferencesAPIs. A SharedPreferences points to a file having key-value pair and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared.

    for full implementation refer here: http://www.mindstick.com/blog/703/Saving%20data%20in%20Android%20Saving%20in%20Key%20Value%20Sets

  2. September 26th, 2012 at 03:06 | #2

    Hakian :
    You have such a high Google ranking and still you don’t have code formatting in your blog?!

    Thumb up!

  3. Hakian
    August 20th, 2012 at 06:14 | #3

    You have such a high Google ranking and still you don’t have code formatting in your blog?!

  1. No trackbacks yet.