2013-03-06 84 views
6

下面的語句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); 
    } 
+0

它是否與在查詢語句中不使用「FROM」相關,以便SQLite無法將其識別爲vaild命令? – 2013-03-07 00:02:50

+0

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

+0

我愛解決方法1:刪除cursor.moveToFirst()...... haha​​ – 2013-03-07 00:34:33

回答

3

我知道你已經解決你的問題,但這裏是發生了什麼演練:

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

1

你可以用這種方式迭代遊標。

if(moveCursor.moveToFirst()){ 
     do{ 
      //your code 

     }while(moveCursor.moveToNext()); 
    }    
+0

我讀過'getCount()'是一個昂貴的操作,所以如果可以的話,避免它可能是明智的http://stackoverflow.com/a/16186513/1084488)。 – Matthias 2014-09-18 14:07:47

+1

沒關係我的上述評論,回顧了Android的源代碼後,我發現,幾乎所有的遊標操作(包括'moveToFirst()','使用MoveToNext() ','isBeforeFirst()'和'isFirst()')將導致至少1次調用'getCount()'。 所以即使'getCount()'很貴也不可避免。此外,我還發現'getCount()'的實現會緩存返回的值,所以至少後續的調用將會很便宜。 – Matthias 2014-09-18 16:01:31