Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: do we need to close Db after closing the cursor

Tags:

android

sqlite

From source code of SQLiteCursor (stack trace):

at android.database.sqlite.SQLiteDatabase.dbclose(Native Method)
at android.database.sqlite.SQLiteDatabase.onAllReferencesReleased(SQLiteDatabase.java:325)
at android.database.sqlite.SQLiteClosable.releaseReference(SQLiteClosable.java:45)
at android.database.sqlite.SQLiteProgram.onAllReferencesReleased(SQLiteProgram.java:119)
at android.database.sqlite.SQLiteClosable.releaseReference(SQLiteClosable.java:45)
at android.database.sqlite.SQLiteProgram.close(SQLiteProgram.java:296)
at android.database.sqlite.SQLiteQuery.close(SQLiteQuery.java:136)
at android.database.sqlite.SQLiteCursor.close(SQLiteCursor.java:506)

Does it mean that, closing the last cursor will also close the Database. And we dont need to close it explicitly, as in this code:

    SQLiteDatabase rdb = db.getReadableDatabase();
    Cursor resultCursor = null;
    String patternQuery = SQLiteQueryBuilder.buildQueryString(true, "Store", columns, where, null, null, null, null);

    try
    {
        resultCursor = rdb.rawQuery(patternQuery, null);


        resultCursor.moveToFirst();
        if (resultCursor.getCount() > 0)
        {
            while (!resultCursor.isAfterLast())
            {
                result.add(resultCursor.getString(0));
                resultCursor.moveToNext();
            }
        }
    }
    catch (Exception e)
    {
        Log.d("DB", "Caught an exception while getting pattern based results: " + e);
    }
    finally
    {
        if (resultCursor != null)
        {
            resultCursor.close();
        }
        if (rdb.isOpen())
        {
            rdb.close();
        }
    }

so here, we dont need to close the rdb?

note: the cursor object keeps the reference to the database, so it gets a lock on same on each query. Therefore 'SQLiteDatabse.dbclose' effectively closes same database.

like image 834
PushpRaj Avatar asked Nov 05 '22 16:11

PushpRaj


1 Answers

You do need to close it. The database will not be closed until you have explicitly closed it and all active cursors have been closed.

like image 88
hackbod Avatar answered Nov 09 '22 03:11

hackbod