Android SQLite API
Android SQLite API
There are a number of different ways that the Android API makes it fairly easy to use our app's
database. The first class we need to get familiar with is SQLiteOpenHelper.
The SQLiteDatabase class is the class that represents the actual database. The
SQLiteOpenHelper class, however, is where most of the action takes place. This class will enable
us to get access to a database and initialize an instance of SQLiteDatabase.
In addition, SQLiteOpenHelper, which we will extend in our Age Database app, has two methods
to override. First, it has an onCreate method, which is called the first time a database is used;
therefore, it makes sense that we would put our SQL to create our table structure in.
The other method we must override is onUpgrade, which, as you can probably guess, is called
when we upgrade our database (use ALTER to change its structure).
2
Databases
We could then build a query like in this next example. The example adds a new entry to our hypothetical
database and incorporates Java variables into the SQL statement: We could then build a query like in this
next example. The example adds a new entry to our hypothetical database and incorporates Java
variables into the SQL statement:
Notice in the previous code that the regular name
and score Java variables are highlighted. The
previous string called query is now the SQL
statement, exactly equivalent to this:
5
Databases
Throughout the typing of the query, Android Studio prompts us as to the names of our variables, making
the chances of an error much lower, even though it is more verbose than simply typing the query.
Now we can use the classes we introduced previously
to execute the query:
When adding data to the database, we will
use execSQL as in the previous code; when
getting data from the database, we will use
the rawQuery method as shown next:
Database cursors
Besides the classes that give us access to the database and the methods that allow us to execute our
queries, there is the issue of exactly how the results we get back from our queries are formatted.
Fortunately, there is the Cursor class. All our database queries will return objects of type Cursor. We can
use the methods of the Cursor class to selectively access the data returned from the queries, as here:
The previous code would output to logcat the two values stored in the first two columns of the result that
the query returned. It is the Cursor object itself that determines which row of our returned data we are
currently reading.
7
Databases
We can access a number of methods of the Cursor object, including the moveToNext method, which
unsurprisingly would move Cursor to the next row, ready for reading: