我想知道如何以静态方式访问我的 Android 应用程序中的 SQLite 数据库。 当我想访问数据库时我总是使用这个:
MySQLiteHelper dbHandler = new MySQLiteHelper(this, "PinDB", null, 4);
这是MySQLiteHelper的构造函数:
public MySQLiteHelper(Context context, String name, CursorFactory factory, int version){
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
现在,我必须以静态方式访问数据库以获取我想要使用的方法。但我不知道如何获取 Activity 的上下文(this)。 我尝试过 getApplicationContext() 等方法,但它们似乎都不起作用。
那么,是否可以更改 MySQLiteHelper(this,"PinDB", null, 4);
变成这样的事情? MySQLiteHelper(MyActivity, "PinDB", null, 4);
如果您需要更多信息,请询问!
提前致谢
最佳答案
我使用 Singleton 来访问 Android 中的 SQLite 数据库。我认为该模式也适合您的用例。
Session.java(Singleton 类)
public class Session
{
private static DbUtil; // static DBUtil
protected Session() {
//
}
public static Session getInstance() {
if (instance == null) {
instance = new Session();
}
return instance;
}
public void initDBUtil(Context ctx){
util = new DbUtil(ctx);
}
public DbUtil getDbUtil()
{
return util;
}
}
DbUtil.java(扩展 SQLiteOpenHelper 的类)
public class DbUtil extends SQLiteOpenHelper
{
public DbUtil(Context context) {
super(context, NAME_DB, null, 1);
// other init code here...
}
// onCreate and other override
}
在入口 Activity 的第一个 onCreate 方法中,只需执行类似的操作:
Session.getInstance().initDBUtil(this);
然后您可以使用 Session 中的 getter 来访问 DbUtil 类:
Session.getInstance().getUtil(). ... your method here ...
关于java - 如何以静态方式访问我的 SQLite 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20806805/