James Dickens James Dickens - 1 year ago 85
Java Question

SQL Lite database persistent storage for Android

I am confused about how to operate an SQL Lite database in Android Studio. What I want is for the user to be able to continually add and search elements in a database. The confusion I have is that it seems most beginner tutorials on this topic will create a database in the MainActivity everytime the "app" is executed which leads me to believe that a new database is created from scratch rather than an old one being updated with new information (or left alone and queried). For instance in a class name DatabaseHelper I have the snippets:

public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);

public void onCreate(SQLiteDatabase db) {
... // Then methods to add, query etc.

And then in the main:

public class MainActivity extends Activity {

protected void onCreate(Bundle savedInstanceState) {
DatabaseHelper db = new DatabaseHelper(this);

... // Then do stuff with the database


Any insights into what I am mis-understand much appreciated.

Answer Source

No, the database is not created every time you run this snippet.

In your example, it is the onCreate method that runs the SQL scripts that create tables. But in the posted code there is no call to this method. That is not an accident. You don't call this method explicitly, Android does, once, when DatabaseHelper is instantiated for the first time.

In the posted code there is a new DatabaseHelper(this);. Contrary to what you might have assumed, this doesn't imply that there will be a call to onCreate. Creating an instance of this class and calling the onCreate method are very different things.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download