Updating sqlite database versions?

后端 未结 2 348
予麋鹿
予麋鹿 2020-12-09 21:57

I have a database that I want to add a column to, I changed the static database version but when I run the program on my device the new column is still not there so I am gue

相关标签:
2条回答
  • 2020-12-09 22:34

    In order to upgrade the Database in Android you should increment the DATABASE_VERSION by one, in order for the SQLOpenHelper to know that it must called the onUpgrade method.

    Rembember

    This only work when you call getWritableDatabase() otherwise it won't upgrade. And if you change the version and call getReadableDatabase it will show an exception

    throw new SQLiteException("Can't upgrade read-only database from version " +
                            db.getVersion() + " to " + mNewVersion + ": " + path);
    

    But Why? You see when you call getWritableDatabase the code check wether the version is the same:

    if (version != mNewVersion) {
                    db.beginTransaction();
                    try {
                        if (version == 0) {
                            onCreate(db);
                        } else {
                            if (version > mNewVersion) {
                                onDowngrade(db, version, mNewVersion);
                            } else {
                                onUpgrade(db, version, mNewVersion);
                            }
                        }
                        db.setVersion(mNewVersion);
                        db.setTransactionSuccessful();
                    } finally {
                        db.endTransaction();
    }
    }
    

    Update

    Well turns out that it should work with getReadableDatabase() since in the code you always are getting a WrittableDatabase too. So it should work with both method, here is the documentation for getReadableDatabase():

    Create and/or open a database. This will be the same object returned by getWritableDatabase() unless some problem, such as a full disk, requires the database to be opened read-only. In that case, a read-only database object will be returned. If the problem is fixed, a future call to getWritableDatabase() may succeed, in which case the read-only database object will be closed and the read/write object will be returned in the future.

    0 讨论(0)
  • 2020-12-09 22:51

    I suggest you increment DATABASE_VERSION by one, that will lead the application to call onUpgrade()

    0 讨论(0)
提交回复
热议问题