SQLite In Android Part 2: The SQLiteOpenHelper

If you’re reading this post, I assume you’ve read the last one on building your contract classes. If not, read through that short post and get up to speed. Part 2 of this segment on using SQLite in Android discusses how to use SQLiteOpenHelper to create the database used in your application. This class is used to manage database creation and updates.

Class Level Variables

In your SQLiteOpenHelper, there are two class level variables you need to record. The database name (including the .db suffix), and the database version:

The database version variable is responsible for handling updates to the database. Any time this variable is incremented, onUpgrade will be called.

Required Implementations

When you extend SQLiteOpenHelper, there are two required methods for you to implement. These are onCreate() and onUpgrade():

As the names imply, onCreate is called when the database is created for the first time, and onUpgrade is called anytime the database version is increased. There is also an onDowngrade() method should you ever need it, but it is not abstract and therefore not a required implementation.

Create Table Statements

You can write the create table statements right inside the onCreate() method, but I’ve chosen to extract them into their own methods for better readability. If you have ever written SQL statements before, the syntax will be very familiar:

For a full explanation of creating an SQLite table, I recommend the SQLite documentation, but I am always available to answer questions in the comments.

That is everything required to create the database for your Android application! There are many more things not discussed here, such as triggers and implementing a database upgrade, but this is sufficient enough to get your database moving forward. You can check out Github to review this entire file, and check out part 3 on the ContentProvider to see how you can read/write from your database!

 

Share this post...
Share on Reddit0Share on Google+0Tweet about this on TwitterShare on LinkedIn0Share on Facebook0

Leave a Reply