Is the onUpgrade method ever called?

后端 未结 6 853
我寻月下人不归
我寻月下人不归 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条回答
  •  春和景丽
    2020-12-07 21:17

    Reviewing all of the posts and running debug code it still was not clear to me when I would see onUpgrade getting called. I was starting to think that Android had a serious flaw..

    The info on this page led me to my final resolution. Thanks a bunch to all contributors!

    This solved it for me...

    public class DatabaseHelper extends SQLiteOpenHelper {
        public static String TAG = DatabaseHelper.class.getName();
        private static final int DATABASE_VERSION = 42;
        private static final String DATABASE_NAME = "app_database";
        private static final String OLD_TABLE = "old_and_useless";
    
        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion ) {
            if( newVersion > oldVersion) {
                Log.d( TAG, "cool! you noticed." );
    
                db.execSQL( "DROP TABLE IF EXISTS " + OLD_TABLE );
                // other calls like onCreate if necessary
    
            } else {
                Log.d( TAG, "Hey! didn't you see me?" );
            }
    
        }
    
        public void checkDatabaseVersion() {
            SQLiteDatabase db = this.getWritableDatabase();
    
            // if the DATABASE_VERSION is newer
            //    onUpgrade is called before this is reached
        }
    
    
        // other code removed for readability...
    }
    

    It's true that getWritableDatabase() and getReadableDatabase() does result in the onUpgrade call. I didn't check other methods since these fit the bill for my needs.

    Keep reading, the kicker is coming...

    This code in my initial Activity enlightened me when I finally realized that the db version was updating during my debugging... ugh!

    DatabaseHelper dbHelper = new DatabaseHelper( this );
    dbHelper.checkDatabaseVersion();
    

    NOTE: calling the DatabaseHelper constructor updates the db version

    After the constructor call, the db was tagged with the new version. Kill the app before a call to getWritableDatabase() or getReadableDatabase() and you're on the new version. Thereafter new executions never call the onUpgrade method until DATABASE_VERSION is increased again. (sigh! now it seems ridiculously obvious :)

    My suggestion is to add some sort of "checkDatabaseVersion()" to the early stages of your app. Alternately, if you create a SQLiteOpenHelper object make sure you call one of the methods (getWritableDatabase(), getReadableDatabase(), etc.) before your app dies..

    I hope this saves someone else the same head scratching!... :p

提交回复
热议问题