简体   繁体   中英

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.

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.

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM