Problem with the book's CursorWrapper Implementations


I am creating my own CursorWrapper classes now and discovered a problem with the way you do this in RunCursor and LocationCursor:

if (isBeforeFirst() || isAfterLast()) return null;

I did the same thing but kept getting null back when I called my getXxxx() method. I found that getCount was returning 20 items. So the cursor is not empty. I don’t know where the Cursor’s pointer is (or why my attempt failed that IF statement when your’s didn’t), but adding this above that if statement fixed it:

Then I saw: [quote]“This method will return false if the cursor is empty.”[/quote]

So, why not just use it instead:

if (!moveToFirst()) { return null; }

Maybe mine is not already pointing at the first row, because it has more than one?


I still recommend the way we did it in the book. The problem with doing moveToFirst() is that it modifies the state of the cursor - after calling it, the cursor will probably be on a different row than it was before you call it. The isBeforeFirst() and isAfterLast() methods don’t modify the cursor, so the check in the book is better for whoever is using the cursor.

Now, you do need to call moveToFirst() - it just needs to be called by whoever is using your CursorWrapper, not the CursorWrapper itself.