Home Tutorials Hints & Tips

Getting Started in Android Development

Part 38 - Creating the SQLite Database

In this tutorial we will complete the database helper we started in the previous tutorial and also create two methods to open and close the database. In the onCreate() method of the DbHelper class we need to execute some SQL code.

public void onCreate(SQLiteDatabase db) {
      + " TEXT NOT NULL, " + KEY_STATUS + " TEXT NOT NULL);");

We use the db.execSQL() method for this. We pass a string into this method that instructs the app to create the database, defining the table and the column of that table. In our example we have the row ID, the member's name and their status. The row ID is defined as an integer, and the remaining columns as text. The statement INTEGER PRIMARY KEY AUTOINCREMENT is significant as this is the column that will be used to identify records. Therefore, we want to increment the row by one for each new records such that each row or record has a unique identifier. The only significance of the + sign is to concatenate the string.

We need to enter the following code for the onUpgrade() method:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

This method is called by the database helper if the database already exists. The drop table statement means that the existing database is deleted, along with all of the data and then the onCreate() method is called to create a new one as defined in the onCreate() method.

Whenever we want to access the database we first need to open it, perform the operation and then close it. We need to define two methods to open and close the database. The method below opens the database.

public MembersDatabase open() throws SQLException {
   databaseHelper = new DbHelper(context);
   memebersDatabase = databaseHelper.getWritableDatabase();
return this;

The key method here is the getWritableDatabase() method. We wish to open our database to be both readable and writeable. The database will remain open until closed. We need to throw an SQLException if the database cannot be opened for any reason.

The method to close the database is quite straightforward.

public void close() {

Notice for both of these method the call to the database helper class. It would be possible to test the methods at this point just to see if there are any error. However, we will leave that for later.

After this tutorial your MembersDatabase.java class should look similar to the one below:

Download Download tutorial set 2

Privacy and Cookies Disclaimer Copyright
© 2015 - 2018 North Border Tech Training All rights reserved