SQLiteDatabases and Cursors

删除回忆录丶 提交于 2020-03-01 04:06:27

问题


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 order 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:


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.



来源:https://stackoverflow.com/questions/5450050/sqlitedatabases-and-cursors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!