Naruto-Uzumaki
Naruto-Uzumaki

Reputation: 21

open and close database Connection in android?

i searched lot questions but i didnt get correct answer. What is the best way to open and close the database in activity lifecycle. please someone help me with correct answer.

Thanks in advance.

Upvotes: 1

Views: 3287

Answers (2)

Govinda P
Govinda P

Reputation: 3319

Use Singleton pattern and access using db=DatabaseHelper.getInstance(context). It guarantees that only one database helper will exist across the entire application lifecycle.

public class DatabaseHelper extends SQLiteOpenHelper { 

  private static DatabaseHelper sInstance;

  private static final String DATABASE_NAME = "database_name";
  private static final String DATABASE_TABLE = "table_name";
  private static final int DATABASE_VERSION = 1;

  public static synchronized DatabaseHelper getInstance(Context context) {

    // Use the application context, which will ensure that you 
    // don't accidentally leak an Activity's context.
    if (sInstance == null) {
      sInstance = new DatabaseHelper(context.getApplicationContext());
    }
    return sInstance;
  }

  /**
   * Constructor should be private to prevent direct instantiation.
   * make call to static method "getInstance()" instead.
   */
  private DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }
}

And access using :

db=DatabaseHelper.getInstance(this);

And also you can close database connection in catch block if needed. I hope it help.

Upvotes: 3

Jinesh Francis
Jinesh Francis

Reputation: 3655

You can open database like this

public void openDataBase() throws SQLException {
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
        }

close database

 public synchronized void close() {
        if (myDataBase != null)
            myDataBase.close();
        //you need to extend the class with SQLiteOpenHelper
         super.close();
    }

Upvotes: 1

Related Questions