【发布时间】:2014-08-11 01:36:40
【问题描述】:
我正在使用 SQLiteOpenHelper 的扩展。我的理解是 onCreate 仅在请求的数据库不存在时运行。 onOpen 应该在每次打开数据库时运行。
这似乎在我的应用程序中的活动之间起作用 - 我需要在每个活动中实例化数据库助手的新实例,并且运行 onOpen 但不运行 onCreate。但是,每次我重新启动应用程序时,都会调用 onCreate。我误解了这应该如何工作还是我只是错误地实施了它?
这是我的助手类:
public class DBWrapper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "MyTest.db";
private static final int DATABASE_VERSION = 2;
public DBWrapper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d("SQLite DBWrapper","OnCreate run");
ver1(db);
ver2(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d("SQLite DBWrapper","OnUpgrade run; oldVer: " + oldVersion + "; newVer: " + newVersion);
if (oldVersion < 2) {ver2(db);}
}
@Override
public void onOpen(SQLiteDatabase db) {
Log.d("SQLite DBWrapper","OnOpen run");
}
private void ver1(SQLiteDatabase db) {
Log.d("SQLite Wrapper","Creating new Version 1");
db.execSQL("create table UserList (ID integer primary key, Name String, State String, Email String, Status String);");
db.execSQL("create table Contacts (ContactID integer, Display_Name String, Email_Address String, IsPrimary integer);");
}
private void ver2 (SQLiteDatabase db) {
Log.d("SQLite Wrapper","Updating to Version 2");
db.execSQL("create table ActivityRecord (UserID String, ActID String, ActDate date, Rating REAL, Comment String, RateDate date, primary key(UserID,ActID));");
}
//Other methods for inserting and retrieving data
}
这就是我在每个活动中创建助手实例的方式:
private DBWrapper DBHelper;
private SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
DBHelper = new DBWrapper(this);
db = DBHelper.getWritableDatabase();
}
每次我重新启动我的应用程序(至少在调试模式下)时,我的 logcat 都会指示 onCreate 正在被调用(连同 ver1 和 ver2)。我做错了什么?
更新:我添加了更多日志记录并发现 A) 这发生在发布和调试变体上; B) 当我在 onCreate 中记录 db.getVersion() 时,它报告“0”。所以这要么意味着它在我关闭并重新打开应用程序时忘记了版本号,要么在应用程序关闭时删除了数据库。
【问题讨论】:
-
你的模拟器/设备是否在退出后保持活动或类似的东西?
-
在我的设备上运行。我不知道你在问什么
-
请发布您的 ContentProvider 课程。
-
我没有使用 ContentProvider。
-
它不应该在每次启动应用程序时再次创建数据库。当您尝试打开一个尚不存在的数据库并且 Android 创建一个新数据库时,您应该只收到
onCreate回调。您不会在项目中的任何地方调用Context.deleteDatabase(...),是吗?
标签: android sqlite activity-lifecycle