Android SQLite - why is my db re-created each time?

…衆ロ難τιáo~ 提交于 2020-01-23 08:14:26

问题


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!


回答1:


the line:

super(context, null, null, VERSION);

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

Android reference



来源:https://stackoverflow.com/questions/8979472/android-sqlite-why-is-my-db-re-created-each-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!