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

I'm trying to better understand the SQLiteOpenHelper class and how and when onCreate and onUpgrade are called.

My problem is that every time I finish and run my application (technically it is actually every time I create a new instance of MyDB), onCreate is called and all the data from the previous use is effectively erased ... WTF ?? ?

At first I ran into this problem by creating a single-user MyDBFactory, where I created a single instance of MyDB. This allowed us to maintain data constancy while the application was running at least.

I would like my schema and data in my database 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 would like to know is why onCreate is called every time I have a β€œnew MyDB (context)”, and where my database goes every time my application exits.

If you have any suitable links or any knowledge that will tell me a little, I would really appreciate it!

+4
source share
1 answer

line:

 super(context, null, null, VERSION); 

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

Android Link

+7
source

Source: https://habr.com/ru/post/1392565/


All Articles