MySQLiteHelper.java (Cont.)

public MySQLiteHelper( Context context ) {
    super( context, database_name, null, database_version ); }
The subclass constructor calls the super method for SQLiteOpenHelper to specify the database name and the current database version.

public void onCreate( SQLiteDatabase database ) {
    database.execSQL( TABLE_CREATE ); }
The method onCreate( ) is called by the framework if the database does not exist. It receives an SQLiteDatabase object as parameter which represents the database. The execSQL command executes a single SQL statement that is not a SELECT or any other SQL statement that returns data. The SQL statement executed is as follows:
   create table  comments(
      _id      integer primary key autoincrement,
      comment  text not null );
The database tables should use the identifier _id for the primary key of the table. Several Android functions rely on this standard. It is the best practice to create a separate class per table. The method is called in the corresponding methods of SQLiteOpenHelper. This way your implementation of SQLiteOpenHelper will stay readable, even if you have several tables.

public void onUpgrade( ... ) {
When the database needs to be upgraded, the system calls the method onUpgrade, which performs the following three steps in this application:
  1. Send a WARN log message and log the exception.
  2. Execute the following SQL command:
       DROP TABLE IF EXISTS comments;
  3. Call the method onCreate as above.
src/main/java/com/example/wenchen/sqlitedemo/MySQLiteHelper.java
package com.example.wenchen.sqlitedemo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySQLiteHelper extends SQLiteOpenHelper {

  public static final String TABLE_COMMENTS = "comments";
  public static final String COLUMN_ID = "_id";
  public static final String COLUMN_COMMENT = "comment";

  private static final String DATABASE_NAME = "applicationdata";
  private static final int DATABASE_VERSION = 1;

  // create table comments (
  //   _id integer primary key autoincrement,
  //   comment text not null );   
  private static final String TABLE_CREATE = "create table "
    + TABLE_COMMENTS + "( " + COLUMN_ID + " integer primary key autoincrement, "
    + COLUMN_COMMENT + " text not null );";

  public MySQLiteHelper( Context context ) {
    super( context, DATABASE_NAME, null, DATABASE_VERSION );
  }

  @Override
  public void onCreate( SQLiteDatabase database ) {
    database.execSQL( TABLE_CREATE );
  }

  @Override
  public void onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion ) {
    Log.w( MySQLiteHelper.class.getName( ), "Upgrading database from version "
      + oldVersion + " to " + newVersion + ", which will destroy all old data" );
    db.execSQL( "DROP TABLE IF EXISTS" + TABLE_COMMENTS );
    onCreate( db );
  }
}