Search code examples
androiddatabasesqliteandroid-sqlite

Android SQLite DB which objects has to be closed


I use the SQLite DB in my Android app. I'm not 100% sure which database objects do I have to close when I'm done with reading/writing with the DB:

For example this code:

public int getLocalSavedPartsAmount() {
    int partsAmount;
    PartsAppDbHelper dbHelper = new PartsAppDbHelper(context);
    SQLiteDatabase db = dbHelper.getReadableDatabase();

    String[] columns = {...};
    Cursor cursor = db.(...);
    partsAmount = cursor.getCount();

    //which one do I have to close here?
    cursor.close(); //1
    dbHelper.close(); //2
    db.close(); //3

    return partsAmount ;
}

Do I need to close 1, 2 and 3? Is it important in which order to close?


Solution

  • You should always close a Cursor when finished with it, a Cursor also requires that the Database is open.

    You don't really need to close the database at all.

    dbHelper.close closes the database(s).

    When you you call getWritableDatabase or getReabableDatabase (this generally gets a writable database anyway), it opens the database and caches it, so generally the same open is used until you close it.

    Opening a database can be quite intensive so you should minimise closes so you don't have to open it again.

    Cusrors, each has an underlying file slot. File slots are limited, use them all and the App will crash.

    So

    public int getLocalSavedPartsAmount() {
        int partsAmount;
        PartsAppDbHelper dbHelper = new PartsAppDbHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
    
        String[] columns = {...};
        Cursor cursor = db.(...);
        partsAmount = cursor.getCount();
    
        //which one do I have to close here?
        cursor.close(); //1
        return partsAmount ;
    }
    

    Would be sufficient.