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

(gtxtreme123) #1
Building Your Initial Database

Put your cursor on the word CrimeTable and key in Option+Return (Alt+Enter). Then select the first
item, Add import for 'com.bignerdranch.android.criminalintent.database.CrimeDbSchema.CrimeTable',
as shown in Figure 14.2.


Figure 14.2  Adding a CrimeTable import


Android Studio will generate an import like this for you:


import com.bignerdranch.android.criminalintent.database.CrimeDbSchema.CrimeTable;


public class CrimeBaseHelper extends SQLiteOpenHelper {


That will let you refer to the String constants in CrimeDbSchema.CrimeTable
by typing in CrimeTable.Cols.UUID, rather than typing out the entirety of
CrimeDbSchema.CrimeTable.Cols.UUID. Use that to finish filling out your table definition code.


Listing 14.6  Creating crime table (CrimeBaseHelper.java)


@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + CrimeTable.NAME + "(" +
" _id integer primary key autoincrement, " +
CrimeTable.Cols.UUID + ", " +
CrimeTable.Cols.TITLE + ", " +
CrimeTable.Cols.DATE + ", " +
CrimeTable.Cols.SOLVED +
")"
);
}


Creating a table in SQLite requires less ceremony than in other databases: You do not have to specify
the type of a column at creation time. It is a good idea to do that, but here you will save a bit of labor
by doing without it.


Run CriminalIntent, and your database will be created. If you are running on an emulator or a rooted
device, you can look at it directly. (Not on an unrooted device, though – it is saved in private storage,
which is secret.)


As of this writing, the emulator images for Nougat (API 24 and 25) do not cooperate with the Android
Device Monitor’s file explorer. To see your files, you will need to install your app on an emulator
running an older version of Android. To remind yourself how to set up an emulator, see the section
called Running on the Emulator in Chapter 1.

Free download pdf