onUpgrade() sqlite database in Android

后端 未结 3 756
说谎
说谎 2020-12-20 15:12

I created an Android application which, check at startup if there is a new version of application. If yes, the application download the new apk file and over-install new apk

相关标签:
3条回答
  • 2020-12-20 15:51

    onUpgrade() is called (you do not call it yourself) when version of your DB changed which means underlying table structure changed etc.

    In general it means that OS is telling you "hey, you asked for database structure version 10 but I found we got something older here, so this is you chance to fix that before you start using database (and potentially crash due to structure mismatch)".

    In that method you should do all that is necessary to, well.. upgrade structure of your old database to structure matching current version requirements like adding/droping columns, converting row contents or even dropping old db completely and create it from scratch - for Android it does not matter what you do here - it's just a sort of emergency callback for your code to do the necessary job (if any). You need to be aware that users may not update frequently so you have to always handle upgrade from version X to Y knowing that X may not be equal to i.e. (Y-1).

    0 讨论(0)
  • 2020-12-20 16:04

    if your are using the SQLiteOpenHelper the onUpgrade will be called whenever you change the DB version. There is an additional requirement for this to work. The db name has to remain the same.

    Old Version:
    dbName = "mydb.db"
    dbVersion = 1
    
    New Version:
    dbName = "mydb.db"
    dbVersion = 2
    

    in the onCreate of the content provider you create an instance of the SQLiteOpenHelper that takes these params. Your SQLiteOpenHelper implementation would look like this:

    public static final class MySQLiteOpenHelper extends SQLiteOpenHelper {
    
            public MySQLiteOpenHelper(Context context, int dbVersion, String dbName) {
                super(context, dbName, null, dbVersion);
            }
    
            @Override
            public void onCreate(SQLiteDatabase db) {
                //Code to create your db here
            }
    
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                // Code to upgrade your db here
            }
    
    }
    

    it will be also called when you alter you table or add more tables in your database

    0 讨论(0)
  • 2020-12-20 16:07

    I found this very helpful https://thebhwgroup.com/blog/how-android-sqlite-onupgrade

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion < 2) {
             db.execSQL(DATABASE_ALTER_TEAM_1);
        }
        if (oldVersion < 3) {
             db.execSQL(DATABASE_ALTER_TEAM_2);
        }
    }
    
    0 讨论(0)
提交回复
热议问题