Android SQLite-为什么每次都要重新创建我的数据库? [英] Android SQLite - why is my db re-created each time?

查看:273
本文介绍了Android SQLite-为什么每次都要重新创建我的数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图更好地理解SQLiteOpenHelper类以及如何以及何时调用onCreate和onUpgrade.

I'm trying to get a better understanding of the SQLiteOpenHelper class and how and when onCreate and onUpgrade are called.

我的问题是,每次我退出并启动应用程序时(从技术上讲,实际上是每次创建MyDB的新实例),都会调用onCreate,并且有效擦除了先前用法中的所有数据... WTF ???

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???

最初,我通过创建一个MyDB实例创建了一个MyDBFactory来解决此问题.这样可以使数据至少在应用程序运行时保持持久.

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!

我基本上有:

   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,以及每次我的应用程序退出时数据库都位于何处.

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!

推荐答案

该行:

super(context, null, null, VERSION);

第二个参数是null,用于指定应在内存中创建数据库,应为其命名.

the second parameter is null specifying that the database should be created in memory, you should give it a name.

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆