Using the Cursor

Before you access a cursor, you should know a few things about an Android cursor:

• A cursor is a collection of rows.

• You need to use moveToFirst() because the cursor is positioned before the first row.

• You need to know the column names.

• You need to know the column types.

• All field-access methods are based on column number, so you must convert the column name to a column number first.

• The cursor is a random cursor (you can move forward and backward, and you can jump).

• Because the cursor is a random cursor, you can ask it for a row count.

An Android cursor has a number of methods that allow you to navigate through it. Listing 3-21 shows you how to check if a cursor is empty, and how to walk through the cursor row by row when it is not empty.

Listing 3-21. Navigating Through a Cursor Using a while Loop if (cur.moveToFirst() == false) {

//no rows empty cursor return;

//The cursor is already pointing to the first row //let's access a few columns int nameColumnIndex = cur.getColumnIndex(People.NAME); String name = cur.getString(nameColumnIndex);

//let's now see how we can loop through a cursor while(cur.moveToNext()) {

//cursor moved successfully //access fields

The assumption at the beginning of Listing 3-21 is that the cursor has been positioned before the first row. To position the cursor on the first row, we use the moveToFirst() method on the cursor object. This method returns false if the cursor is empty. We then use the moveToNext() method repetitively to walk through the cursor.

To help you learn where the cursor is, Android provides the following methods:

isBeforeFirst()

isAfterLast()

isClosed()

Using these methods, you can also use a for loop as in Listing 3-22 to navigate through the cursor instead of the while loop used in Listing 3-21.

Listing 3-22. Navigating Through a Cursor Using a for Loop for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()) {

int nameColumn = cur.getColumnlndex(People.NAME); int phoneColumn = cur.getColumnlndex(People.NUMBER);

String name = cur.getString(nameColumn); String phoneNumber = cur.getString(phoneColumn);

To find the number of rows in a cursor, Android provides a method on the cursor object called getCount().

0 0

Post a comment