嘿 我正在构建一个包含数据库的 Android 应用程序。 我的问题是如何知道应用程序是否已更新? 我的意思是,我知道当 DATABASE_VERSION 来自 -
时,会调用 onUpgrade 方法public DataBaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
this.myContext = context;
}
低于应用程序的版本,但更新后如何增加它,以便应用程序不会一直自行更新?
最佳答案
您无需跟踪版本号。调用 onUpgrade() 后,android 会自动处理所有这些事情。 onUpgrade() 将在下一次更新到期时自动调用(即您再次增加 DATABASE_VERSION)。
更清楚地说:只需保留一个static final int DATABASE_VERSION
字段,每次更改数据库结构上的重要内容时,您都会在开发时增加该字段。
您创建一个扩展 SQLLiteOpenHelper 的类基本上看起来像这样:
public class ContentDatabase extends SQLiteOpenHelper {
// Whenever you change the DB structure, increment DATABASE_VERSION (it starts from 1, so your first upgrade should be 2)
// - note it's only used for upgrades; if it's a new install, onUpgrade won't be called and everything is done by onCreate instead
private static final int DATABASE_VERSION = 6;
public ContentDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
// Code to create the most recent version of your database
// i.e. CREATE TABLE xxx (....)
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Code to update an existing database structure to the most recent
// version.
if (oldVersion < 2) {
// do something to upgrade the DB to version 2
}
if (oldVersion < 3) {
// do something to upgrade the DB to version 3
}
if (oldVersion < 6) {
// Let's assume you added a new table in v4, and then added a field to that new table in v6
if (oldVersion < 4) {
// add the v6 version of the new table to the DB
}
else {
// add the new field to the existing v4 table in the DB
}
}
}
}
每次需要更改表的结构(即添加其他列或表)时,都将 DATABASE_VERSION 变量加一,并为 onCreate() 和 onUpdate() 方法编写相应的代码。这些方法是由android自动调用的。
关于java - 我如何知道何时更新数据库 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5765346/