It's a pretty straightforward question. I'm hoping the answer is "both", but I'm worried it's neither. I've scrutinized the Android developer docs for SQLiteDatabase and Cursor, but can't find any definitive answer to this question.
The case I'm asking about is where I get a cursor, call moveToFirst
, then loop until isAfterLast
returns true. It would be really convenient for a pattern I'm coding a few times if that would just work and execute the loop 0 times if the cursor has 0 records.
Or do I need to explicitly test for an empty cursor first?
EDIT: Some of the responses indicate that people aren't quite getting what I'm asking. Basically, I would like to write this:
cursor = myDb.query(...)
cursor.moveToFirst()
while (!cursor.isAfterLast()) {
processRow(...)
}
But I'm not 100% certain that I can. isAfterLast
can't return anything useful but true for this case, but that doesn't mean it actually does return true for an empty query. The docs don't seem to specify what the return value of most of the cursor methods are if the cursor is empty (the Android docs seem to be unspecific on a lot of corner cases, actually), other than getCount
. So I'm worried that I need to do this:
cursor = myDb.query(...)
if (cusror.getCount() > 0) {
cursor.moveToFirst()
while (!cursor.isAfterLast()) {
processRow(...)
}
}
Which is messier and logically redundant. Bear in mind that in the real implementation there's more code, and this is spread across multiple methods. And one of the answers is now suggesting that I need to check the cursor for null
as well, which is completely undocumented...
I simply want to know whether anyone else knows the actual behaviour of isAfterLast
when called on an empty cursor.
I don't use isAfterLast
. I use the following pattern to read the query result.
SQLiteDatabase db = new DbHelper().getWritableDatabase();
String sql = "SELECT ...";
String[] args = ...;
Cursor cs = db.rawQuery(sql, args);
while (cs.moveToNext()) {
// cs.getXxx(0), cs.getXxx(1)
}
cs.close();
db.close();
DbHelper
is a class that I extend from SQLiteOpenHelper
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With