qb.setTables(getTableName());

 if (isCollectionUri(url)) {

  qb.setProjectionMap(getDefaultProjection ());

 } else {

  qb.appendWhere(getIdColumnName() + '=' + url.getPathSegments().get(1));

 }

 String orderBy;

 if (TextUtils.isEmpty(sort)) {

  orderBy = getDefaultSortOrder();

 } else {

  orderBy = sort;

 }

 Cursor c = qb.query(db, projection, selection, selectionArgs,

  nullnull, orderBy);

 c.setNotificationUri(getContext ().getContentResolver(), url);

 return c;

}

Content providers are explained in greater detail in Part 5 of this book, so some of this you will have to take on faith until then. Here, we see the following:

1. A SQLiteQueryBuilder is constructed.

2. It is told the table to use for the query (setTables(getTableName()) ).

3. It is either told the default set of columns to return (setProjectionMap() ), or is given a piece of a WHERE clause to identify a particular row in the table by an identifier extracted from the Uri supplied to the query() call (appendWhere() ).

4. Finally, it is told to execute the query, blending the preset values with those supplied on the call to query() (qb.query(db, projection, selection, selectionArgs, null, null, orderBy)).

Instead of having the SQLiteQueryBuilder execute the query directly, we could have called buildQuery() to have it generate and return the SQL SELECT statement we needed, which we could then execute ourselves.

Using Cursors

No matter how you execute the query, you get a Cursor back. This is the Android/SQLite edition of the database cursor, a concept used in many database systems. With the cursor, you can do the following:

• Find out how many rows are in the result set via getCount()

• Iterate over the rows via moveToFirst(), moveToNext(), and isAfterLast()

• Find out the names of the columns via getColumnNames(), convert those into column numbers via getColumnIndex(), and get values for the current row for a given column via methods like getString(), getInt(), etc.

• Re-execute the query that created the cursor, via requery()

• Release the cursor’s resources via close()

For example, here we iterate over the widgets table entries from the previous snippets:

Cursor result =

 db.rawQuery('SELECT ID, name, inventory FROM widgets');

result.moveToFirst();

while (!result.isAfterLast()) {

 int id = result.getInt(0);

 String name = result.getString(1);

 int inventory = result.getInt(2);

 // do something useful with these

 result.moveToNext();

}

result.close();

Making Your Own Cursors

There may be circumstances in which you want to use your own Cursor subclass rather than the stock implementation provided by Android. In those cases, you can use queryWithFactory() and rawQueryWithFactory(), which take a SQLiteDatabase.CursorFactory instance as a parameter. The factory, as one might expect, is responsible for creating new cursors via its newCursor() implementation.

Finding and implementing a valid use for this facility is left as an exercise for the reader. Suffice it to say that you should not need to create your own cursor classes much, if at all, in ordinary Android development.

Data, Data, Everywhere

If you are used to developing for other databases, you are also probably used to having tools to inspect and manipulate the contents of the database, beyond merely the database’s API. With Android’s emulator, you have two main options for this.

First, the emulator is supposed to bundle in the sqlite3 console program and makes it available from the adb shell command. Once you are in the emulator’s shell, just execute sqlite3, providing it the path to your database file. Your database file can be found at the following location:

/data/data/your.app.package/databases/your-db-name

Вы читаете Beginning Android
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату