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/EventsData.java

Line 1 package org.example.events;

- import static android.provider.BaseColumns._ID;

- import static org.example.events.Constants.TABLE_NAME; 5 import static org.example.events.Constants.TIME;

- import static org.example.events.Constants.TITLE;

- 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) {

super(ctx, DATABASE_NAME, null, DATABASE_VERSION);

20 @Override

- public void onCreate(SQLiteDatabase db) {

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

- + " INTEGER PRIMARY KEY AUTOINCREMENT, " + TIME + " INTEGER," + TITLE + " TEXT NOT NULL);");

- @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