2

In an Android 'simple' database scenario, is there any benefit or reason to use database.close() and Not databaseHelper.close() ? Is there any benefit or reason to use databaseHelper.close() and Not database.close() ?

Is there a technical reason why both these close methods (shown below) exist?

Thanks, James

MyDatabaseHelper databaseHelper = new MyDatabaseHelper(this);
SQLiteDatabase database = databaseHelper.getWritableDatabase();
   ContentValues valuesToInsert = new ContentValues();
   int id = 0;
   valuesToInsert.put("_id", id);
   valuesToInsert.put("name", "test");
   database.insert("MyRecordsTable", null, valuesToInsert);
database.close();

OR

MyDatabaseHelper databaseHelper = new MyDatabaseHelper(this);
SQLiteDatabase database = databaseHelper.getWritableDatabase();
   ContentValues valuesToInsert = new ContentValues();
   int id = 0;
   valuesToInsert.put("_id", id);
   valuesToInsert.put("name", "test");
   database.insert("MyRecordsTable", null, valuesToInsert);
databaseHelper.close();
James
  • 551
  • 1
  • 5
  • 13

1 Answers1

0

There isn't really a huge difference. This is the whole definition of close() within SQLiteOpenHelper:

/**
 * Close any open database object.
 */
public synchronized void close() {
    if (mIsInitializing) throw new IllegalStateException("Closed during initialization");

    if (mDatabase != null && mDatabase.isOpen()) {
        mDatabase.close();
        mDatabase = null;
    }
}

The reason both exist, is that there may be instances where developers only use SQLiteOpenHelper for interfacing with their database and want the close() method as a convenience to directly access the DB, or vice versa if developers don't choose to use the OpenHelper at all.

anddev84
  • 1,473
  • 12
  • 30