在android中打开和关闭数据库连接?(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.
最满意答案
使用db=DatabaseHelper.getInstance(context)使用Singleton模式和访问。 它保证在整个应用程序生命周期中只存在一个数据库帮助程序。
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块中关闭数据库连接。 我希望它有所帮助。
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.
更多推荐
发布评论