安卓:SQLite,cursor.moveToNext() 总是返回 false

7
以下语句 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);
    }

是否与在查询语句中不使用“FROM”有关,以便SQLite无法将其识别为有效命令? - 運到 等
nop...你的查询应该只返回一行,所以当你使用cursor.moveToFirst()时,你就在第一行了...现在调用moveToNext()将返回false...mCursor不应该为null,所以使用类似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 ... your stuff*/}else{/*cursor has no rows WTF?*/} - Selvin
我爱你宝贝。问题解决了!!!在移除cursor.moveToFirst()之后......哈哈 - 運到 等
2个回答

4
您可以通过以下方式迭代游标。
    if(moveCursor.moveToFirst()){
        do{
            //your code

        }while(moveCursor.moveToNext());
    }               

我已经阅读过 getCount() 是一项昂贵的操作,因此如果可能的话最好避免使用它(请参见 https://dev59.com/Amkw5IYBdhLWcg3wKnib#16186513)。 - Matthias
1
不用在意我之前的评论,经过查看Android源代码,我发现几乎所有的游标操作(包括moveToFirst()moveToNext()isBeforeFirst()isFirst())都会导致至少1次对getCount()的调用。 因此,即使getCount()很耗费资源,也是不可避免的。此外,我还发现getCount()的实现缓存了返回值,所以后续的调用将会更加便宜。 - Matthias

4
我知道您已解决了问题,但是这里是发生的详细过程:
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() mCursor.moveToNext() 中的任意一个。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接