44

I need to know how to retrieve data from cursor. I need this because the ringtonemanager returns all the audio files in form of cursor object, I need to know how to retrieve the values.

Anbudan.

ЯegDwight
  • 24,821
  • 10
  • 45
  • 52
Rakesh
  • 14,997
  • 13
  • 42
  • 62
  • Just read the documentation in the API: http://developer.android.com/reference/android/database/Cursor.html Or there is a nice tutorial: http://developer.android.com/guide/tutorials/notepad/index.html Also this question could maybe help you: http://stackoverflow.com/questions/903343/cursor-get-the-field-value-android – RoflcoptrException May 11 '10 at 12:34

3 Answers3

137

Once you have the Cursor object, you can do something like this:

if (cursor.moveToFirst()){
   do{
      String data = cursor.getString(cursor.getColumnIndex("data"));
      // do what ever you want here
   }while(cursor.moveToNext());
}
cursor.close();
Pulah Nandha
  • 774
  • 4
  • 23
Salvador
  • 1,548
  • 1
  • 10
  • 5
  • There is a ")" missing here: String data = cursor.getString(cursor.getColumnIndex("data")); . Not serious, just to complete your answer. – JJ86 Jun 29 '13 at 13:00
  • Am I right in the sense that even if you are only expecting one row, you need to call cursor.moveToFirst() as else the array containing the data will always be empty??? – AntonSack Apr 30 '15 at 18:26
  • 1
    I thing "!cursor.isAfterLast()" should stay in your while loop, as "Some Noob Student", otherwise it will cause ad infinite loop. – Redauser Mar 13 '16 at 11:27
  • This code will crash trying to call `getString(int)` on a row after the cursor's last row. Look at @tcb answer for a solution that actually works – Nicolás Carrasco-Stevenson Mar 28 '17 at 15:25
  • What's with the "data" here? Is it specific to the question asked? – MrObjectOriented May 04 '19 at 17:37
22

This looks a bit better:

for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
    ...
}
tcb
  • 2,745
  • 21
  • 20
17

Salvador's answer will continue to fetch data from the row after the last row because moveToNext() will only return false when the cursor is pointing at the row after the last row. It will continue to iterate even if the cursor is pointing at the last row.

The correct template should be:

if (cursor.moveToFirst()){
   while(!cursor.isAfterLast()){
      String data = cursor.getString(cursor.getColumnIndex("data"));
      // do what ever you want here
      cursor.moveToNext();
   }
}
cursor.close();
Community
  • 1
  • 1
Some Noob Student
  • 14,186
  • 13
  • 65
  • 103