Some of the applications designed to Android are using SQLite database. Creation of database for the application is slightly easy as you can see on the listing below:

public class MySQLiteHelper extends SQLiteOpenHelper {

    public static final String TABLE_NAME = "comments";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_NAME = "weightDate";

    private static final String DATABASE_NAME = "myappdatabase.db";
    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_CREATE = "creeate table "
            + TABLE_NAME + "(" + COLUMN_ID
            + " integer primary key autoincrement, " + COLUMN_NAME
            + " text not null );";

    public MySQLiteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(DATABASE_CREATE);
    }
}

The piece of code handled in the onCreate method is responsible of database structure creation.

However we could have a bit tricky task during database structure update. Especially when the user is going to upgrade your app from the version which is few versions behind (ie. user has an app with DATABASE_VERSION = 1, but current version of app is using DATABASE_VERSION = 4).

Then we should do the update incrementally. How to handle it presents listing below:

public class MySQLiteHelper extends SQLiteOpenHelper {

    [...]

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {

        int upgradeTo = oldVersion + 1;
        while (upgradeTo <= newVersion) {
            switch (upgradeTo) {
                case 2:
                    sqLiteDatabase.execSQL("some SQL statement to update");
                    break;
                case 3:
                    sqLiteDatabase.execSQL("some SQL statement to update");
                    break;
                case 4:
                    sqLiteDatabase.execSQL("some SQL statement to update");
                    break;
            }
            upgradeTo++;
        }
    }
}

After running onUpgrade method user will have the mostly recent version of database, without missing any data and steps in the middle.

Android – universal method to upgrade database
Tagged on:                 

Leave a Reply

Your email address will not be published. Required fields are marked *

Social Widgets powered by AB-WebLog.com.