2011-03-23 91 views
2

所以我試圖從一個SQLite數據庫的值到遊標,然後選擇一個隨機值。我可以像getString()一樣在該方法中讀取遊標,但是在它返回遊標之後,它無法正常工作。我不知道爲什麼.. 這裏是我從數據庫獲取遊標的方法。它似乎工作正常。Android光標問題

 public Cursor getRandomText(String Rating) 
    { 

     Cursor cursor = myDatabase.query("Elec0RandTexts", new String[] {"Message"}, "Rating=?", 
       new String[]{Rating}, null, null, null); 
     cursor.moveToFirst(); 

     cursor.close(); 

     return cursor; 

    } 

這裏是我的代碼,它返回後讀取光標。

  Cursor result = dbh.getRandomText(Rating); 
     result.moveToFirst(); 

     int RandText = rand.nextInt(result.getCount()); 

     result.moveToPosition(RandText); 
     Toast.makeText(getApplicationContext(), "" + result.getString(RandText), Toast.LENGTH_LONG).show(); 

     result.close(); 

我可能犯了一個愚蠢的錯誤,沒有意識到它,但我無法弄清楚這一點。

感謝,

〜Elec0

+0

你不能在你要返回的光標上調用close(),然後使用它。刪除該行,並在完成後關閉一次。 – LeffelMania 2011-03-23 18:32:15

回答

3

您在返回之前關閉()您的光標。從它返回的位置開始,然後嘗試調用moveToFirst()。如果光標關閉,則無法完成此操作。

在你的getRandomText(String)方法中,你應該從你的Cursor而不是Cursor對象本身返回有意義的數據。這樣,創建遊標的方法就可以繼續關閉遊標了。 (它應該只發生在方法的末尾)

+0

這是真的。那麼我會那樣做。謝謝。 – Elec0 2011-03-23 18:56:23

6
cursor.close(); // in getRandomText() 

之後,你不能獲得光標任何數據 - 它是封閉的。刪除這一行。