0

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);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CreateTable1String);
        db.execSQL(CreateTable2String);
    }
   ... // Then methods to add, query etc. 

And then in the main:

    public class MainActivity extends Activity {  

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
       DatabaseHelper db = new  DatabaseHelper(this); 

... // Then do stuff with the database 

}

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

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
IntegrateThis
  • 853
  • 2
  • 16
  • 39

1 Answers1

1

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.

janos
  • 120,954
  • 29
  • 226
  • 236