Android: onUpgrade not calling at database upgrade

白昼怎懂夜的黑 提交于 2019-12-05 11:25:33
sam

In order to upgrade your database you need to do properly by manipulating the schema I found Both the answers for my questions were useful...

Upgrading database version automatically

anddev84

This is mostly answered in this link: Why is onUpgrade() not being invoked on Android sqlite database?

onUpgrade() will get called in getWriteableDatabase() or getReadableDatabase(), so if you never open the DB for writing or reading specifically, you'd have to manually call through to onUpgrade() or open your database.

To test your onUpgdate you should:

  1. install old version of your app. launch it and let it create a db.
  2. install new version of your app. This should be done with a special adb command: adb install -r. -r key simulates app update process. Without -r key adb install just deletes old version and intalls new one, so onUpgrade doesn't called.

But you better write a test for this purpose. Google it.

I got my answer. The changes I have done are in constructor only as :

public DataBaseHelperClass(Context context) {     
super(context, DATABASE_NAME, null ,DATABASE_VERSION);
this.myContext = context;
//The Android's default system path of your application database.
DB_PATH = "/data/data/com.example.myapp/databases/";
}

and it works for me.

If we use exist database by copy method, we have to set the current DB version to SQLiteDatabase instance. And each time you want upgrade app call getWritableDatabase(), the onUpgrade() function will be called.

public void createDataBase() throws IOException {
    boolean dbExist = checkDataBase();
    Logger.debug(TAG, "checkDataBase dbExist: " + dbExist); 
    if (dbExist) {
        this.getWritableDatabase();
    } else {

        // By calling this method and empty database will be created into
        // the default system path
        // of your application so we are gonna be able to overwrite that
        // database with our database.
        this.getWritableDatabase();

        try {

            copyDataBase();
            Logger.debug(TAG, "copyDataBase SUCCESS"); 
        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }


public SQLiteDatabase openDataBase() throws SQLException {
     String path = mContext.getDatabasePath(DB_NAME).getPath();
    mDataBase = SQLiteDatabase.openDatabase(path, null,
            SQLiteDatabase.OPEN_READWRITE);
    mDataBase.setVersion(DB_VERSION);
    return mDataBase;

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!