1

Is it a good practice to open and close the database for every database transaction operation? let me clear you more.

I have two methods like

public SQLiteDatabase getDatabase() {
    if (database == null || !database.isOpen()) {
        database = getWritableDatabase();
    }
    return database;
}

public void closeDatabase() {
    if (database != null && database.isOpen()) {
        database.close();
    }
}

so every time, when I am updating/inserting or deleting, I am opening the database and closing it.

 public void insert(...) {
      getDatabase().insert(...);
      closeDatabase();
 }

 public void update(...) {
      getDatabase().update(...);
      closeDatabase();
 }

 public void delete(...) {
      getDatabase().delete(...);
      closeDatabase();
 }

remember that all these methods are inside a class DatabaseHelper which is extending SQLiteOpenHelper and there is a global variable private SQLiteDatabase database

and I will perform these operations(insert/update/delete) more frequently.

So my question is Is it a good practice to open and close database for every transaction? if not, what is the good way? Where and When I have to close my database?

RuntimeException
  • 1,201
  • 3
  • 14
  • 25
  • 1
    possible duplicate : http://stackoverflow.com/questions/6608498/best-place-to-close-database-connection – Aduait Pokhriyal Mar 19 '14 at 11:46
  • I always let the db open only for the strict necessary time to consume my data out of it or modify data into it. And close it immediately after. – Phantômaxx Mar 19 '14 at 12:03

1 Answers1

2

Opening and closing the database every time may (un-intentionally) run into problem such as Trying to open an already closed database.

Hence, I would suggest is to have a Singleton for the creating the database object, so that every time you make a call to database = getWritableDatabase(); you refer to the same object.

Consider closing this in onDestroy() method, so that as and when the App closes database is closed too.

private static AllItemsDB db; //AllItemsDB is my database class
public static AllItemsDB getDb() {

    if (db == null) {
        Log.d("","Issue here");
        db = new AllItemsDB(app);
        Log.d("","Issue here not");
    }

    return db;
}

since this is a static method, I can do AllItemsDB.myCRUD_methods and it will return me the same oblect every time and easy to access as well. :)

Help.

Community
  • 1
  • 1
Atul O Holic
  • 6,692
  • 4
  • 39
  • 74