Is the onUpgrade method ever called?

后端 未结 6 860
我寻月下人不归
我寻月下人不归 2020-12-07 20:37

Is the onUpgrade method of SQLiteOpenHelper ever called? If so, when is it called and by what? If it is not called by the developers, then why is it there? What really happe

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 21:21

    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
            }
    
    }
    

提交回复
热议问题