2010-05-11 66 views
32

我需要知道如何從光標檢索數據。我需要這個,因爲ringtonemanager以光標對象的形式返回所有的音頻文件,我需要知道如何檢索值。如何從光標類檢索數據

安布丹。

+0

剛纔看了API的文檔:http://developer.android.com/reference/android /database/Cursor.html或者有一個很好的教程:http://developer.android.com/guide/tutorials/notepad/index.html此外這個問題也許可以幫助你:http://stackoverflow.com/questions/ 903343/cursor-get-the-field-value-android – RoflcoptrException 2010-05-11 12:34:53

回答

108

一旦你的光標對象,你可以做這樣的事情:

if (cursor.moveToFirst()){ 
    do{ 
     String data = cursor.getString(cursor.getColumnIndex("data")); 
     // do what ever you want here 
    }while(cursor.moveToNext()); 
} 
cursor.close(); 
+0

有一個「)」在這裏丟失:String data = cursor.getString(cursor。 getColumnIndex( 「數據」)); 。不嚴重,只是爲了完成你的答案。 – JJ86 2013-06-29 13:00:44

+0

我的意思是,即使你只希望一行,你需要調用cursor.moveToFirst(),否則包含數據的數組將永遠是空的? – AntonSack 2015-04-30 18:26:52

+1

我的東西「!cursor.isAfterLast()」應該留在你的while循環中,就像「Some Noob Student」一樣,否則會導致廣告無限循環。 – Redauser 2016-03-13 11:27:37

14

薩爾瓦多的回答將繼續最後一行之後獲取來自該行的數據,因爲moveToNext()只會返回false當光標指向在最後一行之後的行中。即使光標指向最後一行,它也會繼續迭代。

正確的模板應該是:

if (cursor.moveToFirst()){ 
    while(!cursor.isAfterLast()){ 
     String data = cursor.getString(cursor.getColumnIndex("data")); 
     // do what ever you want here 
     cursor.moveToNext(); 
    } 
} 
cursor.close(); 
20

這看起來好一點:

for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { 
    ... 
}