更新时清除数据 [英] Clear Data on update
问题描述
我在 Android 上维护一个长期存在的应用程序,我决定更改其背后的数据模型,将几个 SQLite 数据库合并为一个新数据库.
I'm maintaining a long living app on Android, and I've decided to change the data model behind it merging a few SQLite databases into a single new one.
问题是,如果我只是创建新数据库并停止使用旧数据库,那么每个应用程序用户的本地存储中仍会保留旧的 SQLite 文件.
The thing is, if I just create the new DB and stop using the old ones, every app user out there will still have the old SQLite files in their local storage.
有没有办法在新版本的应用程序上强制清除数据"?(我正在寻找正确"的方法来做到这一点,我知道我可以检查新数据库是否存在并按照此操作,但我认为可能有更好的方法)
Is there a way to force a "clear data" upon a new version of the app? (I'm looking for the "right" way to do it, I know I can check if the new DB exists and act according, but I think there may be a better way)
谢谢
推荐答案
每当需要升级数据库时(例如,当用户下载新版本的应用程序时),数据库版本号的变化会调用 onUpgrade() 方法,您可以覆盖 SQLiteOpenHelper 类提供的这个方法:
Whenever a database needs to be upgraded(when a user downloads a new version of an app, for example), the change in the database version number calls the onUpgrade() method, you can override thiis method provided with SQLiteOpenHelper class:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("TaskDBAdapter", "Upgrading from version "+oldVersion
+" to "+newVersion
+", which will destroy all old data");
for (String string : table_names)
db.execSQL("drop table if exists "+ string);
onCreate(db);
}
这篇关于更新时清除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!