Search code examples
androidupgrade

upgrade android app , how to override sqlite


i have a android app of version 4.20 inside 10M sqlitedb, now i have a app of version 4.21 inside 100M sqlitedb,i want upgrade 4.20 to 4.21, when it upgrade have completed, i find the sqlite size still keep 10M in 4.21 app.

so the question is how to override sqlitedb when upgrade app 4.20 -> 4.21 。


My business is: app will have a lot of data synchronization. In order to optimize, every app will fill in initialization data into SQLite when it is published. Therefore, after each app have upgraded, I hope to completely overwrite SQLite。

any help is very apprecated.


Solution

  • You can upgrade your database version and in the onUpgrade() method of your SQLiteOpenHelper drop all tables and call onCreate() method for recreat database.

    public class MyOpenHelper extends SQLiteOpenHelper {
    
        ...
    
        private void resetDB(SQLiteDatabase db) {
            
            // Drop all tables 
            db.execSQL("DROP TABLE IF EXISTS table_name");
            // TODO duplicate above line for other tables
            
            // Crate tables again
            onCreate(db);
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            resetDB(db);
        }
    
        @Override
        public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            super.onDowngrade(db, oldVersion, newVersion);
            resetDB(db);
        }
    }