Cursor

Cursor can handle one or more rows based on source query. Cursor is map of data and will contain as many rows as source(select) query returns. So if query returns hundred rows, these rows are inserted to Cursor and Cursor contain these hundred rows.

You can imagine Cursor as map of data with dynamic size(similar as List) where data are placed as « rows ». Each row has own row id(row number, we can say some pointer) that is generated gradually as they are inserted to Cursor and you can simply move between rows with this number. Implicitly each Cursor has « actual pointer » positioned before first row(-1 position) so if you call c.getString(0)expection will be thrown because there is nothing to retrieve.

So always you have to call cursor.moveToFirst() that prepare Cursor for reading and if is empty, method return false because there is no row.

The best looking way I’ve found to go through a cursor is the following:

Cursor cursor;
... //fill the cursor here

for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
    // do what you need with the cursor here
}

Don’t forget to close the cursor afterwards

cursor.close();

Laisser un commentaire

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur la façon dont les données de vos commentaires sont traitées.

Articles récents
Commentaires récents
fatima dans Bienvenue !
AdminDroid dans Bienvenue !
fatima dans Bienvenue !
Archives
Catégories