Search code examples
javaandroidcursor

How does Cursor work in android


I'm having a hard time exactly visualizing 'Cursor' functionality in my program. I kind of get the jist of it, but can anyone explain it's functionality in detail?

By Cursor, I mean the Cursor interface. I can't simply understand the role it plays with anything.

http://developer.android.com/reference/android/database/Cursor.html


Solution

  • A Cursor object is returned from a query on a SQLite database. It will return all rows that the query returns.

    Say you have a table called names in your database database configured as such:

    _id     _name
    1       Space Ghost
    2       Zorak
    3       Moltar
    4       Brak
    

    If you want to get all data from this table and use it, you would do something like this:

    public HashMap<Integer, String> getNames(){
    
     HashMap<Integer, String> data = new HashMap<Integer, String>();
    
     try{
      SQLiteOpenHelper helper = new MyOpenDbHelper(context);
      SQLiteDatabase db = helper.getReadableDatabase();
      String selectQuery = "SELECT  * FROM names";
      Cursor cursor = db.rawQuery(selectQuery, null);
      if (cursor != null && cursor.moveToFirst()){ //make sure you got results, and move to first row
        do{
            int mID = cursor.getInt(0); //column 0 for the current row
            String mName = cursor.getString(1); //column 1 for the current row
            data.put(mID, mName);
    
          } while (cursor.moveToNext()); //move to next row in the query result
    
      }
    
     } catch (Exception ex) {
        Log.e("MyApp", ex.getMessage());
     } finally
     {
        if (cursor != null) {
           cursor.close();
    
        }
        if (db != null) {
            db.close();
        }
    
     }
    
    return data;
    }
    

    Usually you will create your own class to extend SQLiteOpenHelper, as such:

    public class MyOpenDbHelper extends SQLiteOpenHelper {
         //........
    }