Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 14  SQLite Databases


A SQLiteOpenHelper is a class designed to get rid of the grunt work of opening a SQLiteDatabase.
Use it inside of CrimeLab to create your crime database.


Listing 14.4  Opening a SQLiteDatabase (CrimeLab.java)


public class CrimeLab {
private static CrimeLab sCrimeLab;


private List mCrimes;
private Context mContext;
private SQLiteDatabase mDatabase;
...
private CrimeLab(Context context) {
mContext = context.getApplicationContext();
mDatabase = new CrimeBaseHelper(mContext)
.getWritableDatabase();
mCrimes = new ArrayList<>();
}


(Wondering why the context is stored in an instance variable? CrimeLab will use it in Chapter 16.)


When you call getWritableDatabase() here, CrimeBaseHelper will do the following:



  • Open up /data/data/com.bignerdranch.android.criminalintent/databases/crimeBase.db,
    creating a new database file if it does not already exist.

  • If this is the first time the database has been created, call onCreate(SQLiteDatabase), then save
    out the latest version number.

  • If this is not the first time, check the version number in the database. If the version number in
    CrimeBaseHelper is higher, call onUpgrade(SQLiteDatabase, int, int).


The upshot is this: You put your code to create the initial database in onCreate(SQLiteDatabase),
your code to handle any upgrades in onUpgrade(SQLiteDatabase, int, int), and it just works.


For now, CriminalIntent will only have one version, so you can ignore onUpgrade(...). You only
need to create your database tables in onCreate(SQLiteDatabase). To do that, you will refer to the
CrimeTable inner class of CrimeDbSchema.


The import is a two-step process. First, write the initial part of your SQL creation code.


Listing 14.5  Writing first part of onCreate(SQLiteDatabase)


(CrimeBaseHelper.java)


@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + CrimeDbSchema.CrimeTable.NAME);
}

Free download pdf