Search code examples
androiddatabase-schemaandroid-install-apk

Perform specific operation at the time of installing apk?


I have updated the application's database. But users who have updated the application from market will see a crash everytime app is started because new database structure is not compatible with old database. Its not good to ask them to uninstall and install the app, I need to perform an operation just for single time at the time of installation i.e. clear the old database and create new one. This should not be called everytime the app starts, only at the time of installation..or when the app starts for the first time.

I think I have clearly defined my situation, now where do I go from here? Should I bug users to uninstall and install app or its possible to do what I have asked?


Solution

  • Just change the version of your database and by overriding onUpgrade on your DatabaseHelper class.

        private static final int DATABASE_VERSION = 2;
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
                    + ", which will destroy all old data");
    
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_CREATION);
            onCreate(db);
        }