Android SQLite - 为什么我的数据库每次都重新创建?
我试图更好地理解 SQLiteOpenHelper 类以及 onCreate 和 onUpgrade 的调用方式和时间。
我的问题是,每次我退出并启动我的应用程序(从技术上讲,实际上是每次我创建 MyDB 的新实例时),都会调用 onCreate ,并且之前使用的所有数据都会被有效擦除......WTF???
我最初通过创建一个单例 MyDBFactory 来解决这个问题,在其中创建了一个 MyDB 实例。这使得数据至少在应用程序运行时保持不变。
我希望我的数据库模式和数据能够持久!
我基本上有:
public class MyDB extends SQLiteOpenHelper{
private static int VERSION = 1;
...
public ContactControlDB(Context context) {
super(context, null, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
db.execSQL(INSERT_DATA);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
和:
public class MyDBFactory{
private static MyDB db;
public static MyDB getInstance(Context context) {
if(db == null) {
db = new MyDB (context);
}
return db;
}
}
我想知道的是为什么每次我有“new MyDB(context)”时都会调用 onCreate,以及每次我的应用程序退出时我的数据库会去哪里。
如果您有一些适当的链接或一些可以帮助我了解的知识,我将不胜感激!
I'm trying to get a better understanding of the SQLiteOpenHelper class and how and when onCreate and onUpgrade are called.
My problem is that each time I quit and start my application (technically it's actually each time I create a new instance of MyDB), onCreate is called, and all of the data from the previous usage is effectively wiped... WTF???
I got around this problem initially by creating a singleton MyDBFactory where I created a single instance of MyDB. This allowed the data to be persistent while the application is running at least.
What I would like is for my database schema and data to be persistent!
I basically have:
public class MyDB extends SQLiteOpenHelper{
private static int VERSION = 1;
...
public ContactControlDB(Context context) {
super(context, null, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
db.execSQL(INSERT_DATA);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
and:
public class MyDBFactory{
private static MyDB db;
public static MyDB getInstance(Context context) {
if(db == null) {
db = new MyDB (context);
}
return db;
}
}
What I'd like to know is why onCreate is called every time I have 'new MyDB(context)', and where my database goes each time my app exits.
If you have some appropriate links, or some knowledge that would clue me up a bit, I'd greatly appreciate it!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该行:
第二个参数是
null
指定数据库应在内存中创建,您应该给它一个名称。Android 参考
the line:
the second parameter is
null
specifying that the database should be created in memory, you should give it a name.Android reference