【问题标题】:Android: SQLite, cursor.moveToNext() always returns falseAndroid:SQLite,cursor.moveToNext() 总是返回 false
【发布时间】:2013-03-06 23:59:08
【问题描述】:

以下语句cursor.moveToNext() 总是错误的。我希望循环执行一次。我已经测试了查询实际上返回了数据。

有谁知道这是怎么回事?

    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 应该永远不要为空,所以使用像 if(mCursor.moveToFirst()){do{/*String res... your stuff*/}while(mCursor.moveToNext());}else{/*cursor has no rows should not happend*/} 这样的 smth 或者在这种情况下(因为它应该只返回 1 行 if(mCursor.moveToFirst()){/*String res... your stuff*/}else{/*cursor has no rows WTF?*/}
  • 我爱你宝贝。问题解决了!!!去掉 cursor.moveToFirst() 之后……哈哈

标签: android sql sqlite


【解决方案1】:

我知道你已经解决了你的问题,但这里是发生的事情的演练:

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()

【讨论】:

    【解决方案2】:

    你可以这样迭代光标。

        if(moveCursor.moveToFirst()){
            do{
                //your code
    
            }while(moveCursor.moveToNext());
        }               
    

    【讨论】:

    • 我听说getCount() 是一项昂贵的操作,所以如果可以的话最好避免它(参见stackoverflow.com/a/16186513/1084488)。
    • 别在意我上面的评论,在查看了 Android 源代码后,我发现几乎所有的光标操作(包括 moveToFirst()moveToNext()isBeforeFirst()isFirst())都会导致至少 1 次致电 getCount()。因此,即使getCount() 很昂贵,它也是不可避免的。而且我还发现getCount()的实现会缓存返回值,所以至少后续调用会很便宜。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2021-11-05
    • 2018-11-05
    • 2019-05-06
    • 2017-04-29
    • 2013-04-30
    相关资源
    最近更新 更多