0

Why do we have to move to the first item in the code below? I thought the cursor would only contain one row since the rowId is a primary key

    // Fetch single reminder
@SuppressLint("NewApi")
public Cursor fetchReminder(long rowId) throws SQLException {
    Cursor myCursor = db.query(true, DATABASE_TABLE, new String[] {
            KEY_ROW_ID, KEY_TITLE, KEY_BODY, KEY_DATE_TIME }, KEY_ROW_ID
            + "=" + rowId, null, null, null, null, null, null);
    if (myCursor != null) {
        myCursor.moveToFirst();
    }
    return myCursor;
}
Braith Vince
  • 21
  • 1
  • 3

1 Answers1

0

There is only one Cursor class. It cannot known how many rows it have. The Query does not create different types of cursors for querying a single row or many. You should just call:

Curcor c = db.query(...);
try {
    if (c.moveToFirst()) { // we only have 1 result. 
                           //Otherwise we would iterate by
                           //(while(c.moveToNext()){...}
        String value = c.getString(0);
    }
} finally {
    c.close();
}
Paul Woitaschek
  • 6,717
  • 5
  • 33
  • 52
  • Okay..but if we know that the result is only going to comprise of one row..why should we say c.moveToFirst ? – Braith Vince Mar 28 '15 at 19:42
  • Because this way you can check if there is at least one row like expected and dont get an npe when reading the values. And I think (not 100% sure) that the default index we are in cursor is -1, so we have to go to the first. – Paul Woitaschek Mar 28 '15 at 20:03