Tuesday, 6 June 2017

Upgrade existing Database

When we want to add some new field in existing data base and Don't want to lose old data of user? What we have to do in such situation?
Solution: - While giving updates to android application , some time we are making some changes in database such as adding a new field but the main problem is that our application is live,so we need to take care of user's existing data which is stored in databaseSQLite provides onUpgrade() method to overcome such situation. onUpgrade() is called when database version is changed which means that your database table structure having some changes. Just follow the following steps
  • To add a new column into the existing table, fire "Alter" query in onUpgrade() method of SQLiteOpenHelper 
  • Change version of database(you can not downgrade version of database)
  • 1
    2
    3
    4
    5
    6
    7
    8
    public class DBManager extends SQLiteOpenHelper {
     private SQLiteDatabase sqLiteDatabase;
     private int dbVersion = 2; //changed version
    
            private DBManager(Context context) {
                super(context,"DbSample", null, dbVersion);    
     }
    }
      Remember one thing  onUpgrade() method is called only when version of database  is changed
  • Now write alter query in onUpgrade()
  • 1
    2
    3
    4
    5
    6
     @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
            if (newVersion > oldVersion) {
                sqLiteDatabase.execSQL("ALTER TABLE " + tbName + " ADD  COLUMN roll INTEGER DEFAULT 0");
            }
        }

No comments:

Post a Comment

Create File on External Storage using Storage access framework for android 10

How To Create File on External Storage on android 10 using Storage Access Framework? By default, apps targeting Android 10 and higher a...