【发布时间】:2016-06-01 07:53:00
【问题描述】:
我搜索了很多问题,但我没有得到正确的答案。 在活动生命周期中打开和关闭数据库的最佳方法是什么。 请有人帮助我正确答案。
提前致谢。
【问题讨论】:
-
为此使用单例模式,因此您无需在活动生命周期中处理它。 androiddesignpatterns.com/2012/05/…
我搜索了很多问题,但我没有得到正确的答案。 在活动生命周期中打开和关闭数据库的最佳方法是什么。 请有人帮助我正确答案。
提前致谢。
【问题讨论】:
使用单例模式并使用db=DatabaseHelper.getInstance(context) 访问。
它保证在整个应用程序生命周期中只存在一个数据库助手。
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);
}
}
并使用:
db=DatabaseHelper.getInstance(this);
如果需要,您还可以在 catch 块中关闭数据库连接。 希望对你有帮助。
【讨论】:
when 解释应该打开和关闭连接。据我所知,用户希望在应用程序期间使用数据库,并希望知道何时开始连接以及何时结束连接。例如,数据库应该在 "MainActivity".onCreate() 中打开,并在 "MainActivity".onDestroy 中关闭,这样,数据库可以在整个堆栈中使用,同时在单点进行管理。否则,它也可以在 ApplicationContext 中完成,但关闭会更难(不知道应用程序)
你可以这样打开数据库
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
关闭数据库
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
//you need to extend the class with SQLiteOpenHelper
super.close();
}
【讨论】: