2013-06-27 47 views
0

我有兩個按鈕。一個用於前一個,另一個用於下一個sqlite數據庫記錄。Android數據庫遊標行爲奇怪

這是我如何試圖從數據庫中獲取下一條記錄。

public long getNext(int id,DataBaseHelper helper){ 

    Story story = new Story(); 

    Cursor cursor = story.getStories(helper, 0); 

      //Updated code  

    cursor.moveToPosition(id); 

    cursor.moveToNext(); 

    return cursor.getLong(1); 

      //Updated code 

} 

問題是,如果我通過它的前一個位置是「1」,我得到的下一個位置是「3」。爲什麼它跳過一條記錄?它每次都會跳過一條記錄。請告訴我,如果我做錯了什麼,因爲我在這方面是新手,我已經到處尋找,但這個具體問題似乎正在發生在我身上。

UPDATE:代碼編輯,以表現出更好的方法(也許)

回答

0

好的。我在這裏的做法有點不對。我忽略了遊標索引從-1開始並且我的表的數據庫索引從1開始的事實。所以我必須從id變量中減去-1,並且它解決了問題:)以下代碼適用於我。

public long getNext(int id,DataBaseHelper helper){ 

      id = id - 1;   

    Story story = new Story(); 

    Cursor cursor = story.getStories(helper, 0); 

      //Updated code  

    cursor.moveToPosition(id); 

    cursor.moveToNext(); 

    return cursor.getLong(1); 

      //Updated code 

} 
0

記住Cursor.getPosition()開始從0計數因此,第一條記錄在索引#0,在索引#1,第二個,.. 。

看看官方文檔:Cursor.moveToPosition(int position)

讓我們來看看你的代碼:

ID = 1,爲例子)

cursor.moveToPosition(id); 

// Cursor is now on the record #1, so the second one of the list 

cursor.moveToNext(); 

// Cursor is now on the record id+1 = #2, so the third one of the list 

return cursor.getLong(1); 

// Returns the value of the colon #1 of the third record 
// of the list : so the record at the index #2 
+0

好的。我已經移除movetofirst()。但它仍然跳了一個記錄。 – xmaestro

+0

剛剛編輯,以適應您的新版本 – mithrop

+0

好男人基於您的迴應我調整了我的代碼爲id,它的工作。謝謝:) – xmaestro