Using SQLite OpenHelper

Next we create a helper class called EventsData to represent the database itself. This class extends the Android SQLiteOpenHelper class, which manages database creation and versions. All you need to do is provide a constructor and override two methods.

Download Eventsv1/src/org/example/events/

Line 1 package;

- import static android.provider.BaseColumns._ID;

- import static; 5 import static;

- import static;

- import android.content.Context;

- import android.database.sqlite.SQLiteDatabase;

- import android.database.sqlite.SQLiteOpenHelper; 10

- public class EventsData extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "events.db"; private static final int DATABASE_VERSION = 1;

15 /** Create a helper object for the Events database */

- public EventsData(Context ctx) {


20 @Override

- public void onCreate(SQLiteDatabase db) {

db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + _ID


- @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 30 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

The constructor starts on line 16. DATABASE_NAME is the actual filename of the database we'll be using (events.db), and DATABASE_VERSION is just a number we make up. If this were a real program, you would increase the version number whenever you had to make significant changes to the database design (for example, to add a new column).

The first time you try to access a database, SQLiteOpenHelper will notice it doesn't exist and call the onCreate() method to create it. On line 21, we override that and run a CREATE TABLE SQL statement. This will create the events table and the events.db database file that contains it.

When Android detects you're referencing an old database (based on the version number), it will call the onUpgrade() method (line 28). In this example, we just delete the old table, but you could do something smarter here if you like. For example, you could run an ALTER TABLE SQL command to add a column to an existing database.

0 0

Post a comment