安卓:SQLite的,cursor.moveToNext()始终返回false
下面的语句cursor.moveToNext()
永远是假的。我期望循环执行一次。我测试过查询实际返回数据。安卓:SQLite的,cursor.moveToNext()始终返回false
有谁知道是怎么回事?
String query ="SELECT(SELECT COUNT(*) FROM Table1) as count1, (SELECT COUNT(*) FROM Table2) as count2;";
Cursor mCursor = mDb.rawQuery(query, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
while (cursor.moveToNext()) { //<---------------return false here???
String result_0=cursor.getString(0);
}
我知道你已经解决你的问题,但这里是发生了什么演练:
Cursor mCursor = mDb.rawQuery(query, null);
// At this point mCursor is positioned at just before the first record.
if (mCursor != null) {
mCursor.moveToFirst();
// mCursor is now pointing at the first (and only) record
}
while (mCursor.moveToNext()) {
String result_0=cursor.getString(0);
}
// The loop above was skipped because `.moveToNext()` caused mCursor
// to move past the last record.
所以,在你只需要一个记录的情况下,你只需要要么mCursor.moveToFirst()
OR您的mCursor.moveToNext()
。
你可以用这种方式迭代游标。
if(moveCursor.moveToFirst()){
do{
//your code
}while(moveCursor.moveToNext());
}
我读过'getCount()'是一个昂贵的操作,所以如果可以的话,避免它可能是明智的http://stackoverflow.com/a/16186513/1084488)。 – Matthias 2014-09-18 14:07:47
没关系我的上述评论,回顾了Android的源代码后,我发现,几乎所有的游标操作(包括'moveToFirst()','使用MoveToNext() ','isBeforeFirst()'和'isFirst()')将导致至少1次调用'getCount()'。 所以即使'getCount()'很贵也不可避免。此外,我还发现'getCount()'的实现会缓存返回的值,所以至少后续的调用将会很便宜。 – Matthias 2014-09-18 16:01:31
它是否与在查询语句中不使用“FROM”相关,以便SQLite无法将其识别为vaild命令? – 2013-03-07 00:02:50
nop ...你的查询应该只返回一行,所以当你使用cursor.moveToFirst()你在第一行...现在任何调用moveToNext()将返回false ... mCursor不应该为null,所以使用smth像if(mCursor.moveToFirst()){do {/ * String res ... your stuff * /} while(mCursor.moveToNext());} else {/ * cursor has no rows should not happend * /}'或在这种情况下(因为它应该只返回1行'if(mCursor.moveToFirst()){/ * String res ...你的东西* /}否则{/ *光标没有行WTF?/}' – Selvin 2013-03-07 00:13:01
我爱解决方法1:删除cursor.moveToFirst()...... haha – 2013-03-07 00:34:33