Cursor loop iteration not displaying first value
So, I have a query returning a Cursor with all values (I confirmed this with cursor.getCount() where the int returned was equivalent to the number of records in the database), but for some reason, no matter what iteration-loop I write I can never seem to retrieve the first value of the list.
private void addAllUnsentCrapportsToList() {
mDbAdapter.open();
Cursor cursor = mDbAdapter.getAllCrapports();
cursor.moveToFirst();
String text = "";
while(cursor.isAfterLast() == false){
text = text
+ "typ: " + cursor.getString(cursor.getColumnIndex(DbAdapter.CRAPPORT_K开发者_如何学编程EY_GARBAGETYPE))
+ " kommentar: " + cursor.getString(cursor.getColumnIndex(DbAdapter.CRAPPORT_KEY_COMMENT))
+ "\n";
cursor.moveToNext();
}
unsentCrapportList.setText(text);
}
This bit of code displays all the values, excluding the first. What am I doing wrong? I've tried numerous approaches, including do while, while etc, but have always ended up with the same fault.
What am I missing?
I dont see anything wrong with your code. So maybe you are not getting the first value from the db
? Have you tried to print the data just after cursor.moveToFirst();
to see which is the first element?
Turns out there was nothing wrong with the code. I had to to a "project clean" in Eclipse and then restart the emulator. Thanks to all answers anyhow.
it might be even better to use
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
// Your code
}
}
cursor.moveToFirst();
while (cursor.moveToNext()) {
// Your code
}
This has never failed me. Try it and see how it goes?
Do some logging with LOG to see what you are getting and check out how the database looks with http://sourceforge.net/projects/sqlitebrowser/
Edit: Btw, any particular reason you don't use startManagingCursor(cursor);
? Probably not causing the error, just wondering, since it seems handy.
精彩评论