7

My code is like below:

Cursor getResults() {
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, null, null,
                        null, null, null);
    db.close();
    return c;
}

My question is, after db.close() is executed, is the cursor c still alive and navigable?

Thanks.

Kai
  • 3,775
  • 10
  • 39
  • 54

1 Answers1

8

No. You do not want to use a cursor while the database is closed. When you call close(), it makes the object (and it's corresponding cursor) invalid.

DeeV
  • 35,865
  • 9
  • 108
  • 95
  • 2
    Then I don't know when I should close the database, since the cursor is returned to be use by other activities. Any suggestions? – Kai Jun 28 '11 at 22:08
  • 4
    The easiest, and probably safest, way to handle database queries is to open it, get the data you need, close the cursor, close the database, then return the requested results. Cursors are only meant to traverse database query results. You generally don't want persistent connections. In this case, you can put the results in a collection of some sort and return that. – DeeV Jun 29 '11 at 12:15