开发者

Does an Android database get completely removed and recreated then updating an app?

I have an app that uses a database. At startup I check to see if my tables are missing and if so I create them. Works great. I've noticed that if I "adb uninstall" then the next time I run my app the tables are created again (this is what I need), but what about when updating through the mark开发者_StackOverflow社区etplace? I'm in the process of releasing an update, and I've made major changes to the tables. I'd like it if the tables were completely wiped and re-created, in fact my app needs this to happen. If someone updates and has the old tables then there will be a force close. Does anyone know the specifics of this scenario?

My tables are only for lookup, I store no user data so I dont really care about losing data on the updates. Of course I know an option is to use some type of "version" table and check to see if I need to manually drop and create, but I was wondering if that was even needed. Thanks.


On an update the tables are left alone. I'm going to assume you have implemented a subclass of SQLiteOpenHelper to explain this. The way Android is able to handle version changes is through the use of onUpgrade in the SQLiteOpenHelper class. This method is called from SQLiteOpenHelpers constructor if the DB version is older than the version the app expects. From inside onUpgrade is where you are going to drop your old tables and create the new ones.

onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion){
 Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            //we can change this to perform different behaviors
            db.execSQL("DROP TABLE IF EXISTS "+MYDB.TABLE_NAME);
            onCreate(db);
}

It is important to note the way Android tells if you are using a new DB version.

DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

That field DATABASE_VERSION is used, so you should use a final static int member as part of your DB implementation.

Hope that helps, leave me a comment if you have questions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜