Search code examples
androidsqliteandroid-sqlite

How Upgrade SQLite Data without losing old version data in Android?


I have one app which I already published V1 which have an SQLite Database but in V2 I updated Database Schema, My question is this how do I migrate database without losing data which already exists.


Solution

  • My question is this how do I migrate database without losing data which already exists.

    It's possible. You should read onUpgrade at first.

    public abstract void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion)

    Called when the database needs to be upgraded. The implementation should use this method to drop tables, add tables, or do anything else it needs to upgrade to the new schema version.

    EXAMPLE

    If you add new column then,

    @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {      
              Log.e("VERSION", "Updating table from " + oldVersion + " to " + newVersion);
               if (oldVersion < Your_New_version){
                db.execSQL("ALTER TABLE " + TABLE_NAME  + " ADD COLUMN new_column_name TEXT;");
            }
    
        }