2010-05-11 70 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()) { 
    ... 
}