开发者

SQLiteDatabases and Cursors

I was wondering if someone could give me a brief overview of Android Cursors. A couple of specific questions:

1 - I have a method which returns a cursor after a database query:

    public static Cursor getVehicles()
{
    SQLiteDatabase db = vehicleData.getReadableDatabase();
    Cursor cursor = db.query(TABLE_NAME, GET_VEHICLES_FROM_CLAUSE, null, null, null, null, ORDER_BY);

    return cursor;
}

In or开发者_JAVA百科der to do housekeeping, I tried db.close() just before the return statement. However, this caused the returned cursor to contain no rows. Why is this?

2 - What's the difference between closing a cursor and closing a database?

3 - Do I need to call close on a Cursor if it is a local variable, or can I leave it to the garbage collector to clean up?

4 - My database is small and only used by my application - can I just keep it open?


1) The cursor is just a pointer to the data returned by your query, it doesn't contain all the data from your query. This is to increase performance/efficiency (large resultsets aren't read at once -> less memory used). Therefore, if you close the database, the cursor can't retrieve the data -> it's empty.

2) When you close a cursor, all associated resources are released -> you can't access the data associated with this cursor (since it has been released), but you can make new queries using this or other cursors. When you close a database, you can't query it anymore (until you re-open it).

3) Always close cursors. Otherwise you will run into problems - the GC will complain if the cursor isn't closed and new queries are blocked.

4) If you close it when your app finishes, yes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜