如何访问我的SQLite数据库以静态的方式? [英] How can I access my SQLite Database in a static way?
问题描述
我想知道我怎么能访问我的SQLite数据库在我的Android应用程序在一个静态的方式。
当我要访问数据库,我总是用这样的:
I was wondering how I could access my SQLite database in my android app in a static way. I always use this when I want to access the database:
MySQLiteHelper dbHandler = new MySQLiteHelper(this, "PinDB", null, 4);
这是MySQLiteHelper的构造:
This is the constructor of MySQLiteHelper:
public MySQLiteHelper(Context context, String name, CursorFactory factory, int version){
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
现在,我要访问数据库在一个静态的方式,因为我想用的方法。但我不知道我怎么能拿活动(本)的情况下。
我已经试过类似的方式getApplicationContext()等,但他们似乎都没有工作。
Now, I have to access the database in a static way for a method I want to use. But I have no idea how I could get the context of the activity (this). I've tried ways like getApplicationContext() etc. but they all don't seem to work.
那么,是不是可以改变 MySQLiteHelper(这一点,PinDB,NULL,4);
弄成这个样子? MySQLiteHelper(MyActivity,PinDB,NULL,4);
So, is it possible to change MySQLiteHelper(this,"PinDB", null, 4);
into something like this? MySQLiteHelper(MyActivity, "PinDB", null, 4);
如果您需要任何更多的信息,请不要问!
If you need any more information, please do ask!
在此先感谢
推荐答案
我使用单访问SQLite数据库中的Android。我认为模式适合您的使用情况也是如此。
I use a Singleton to access the SQLite Database in Android. I think that pattern fits your use case as well.
Session.java(单例类)
Session.java (the Singleton class)
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)
DbUtil.java (the class extending SQLiteOpenHelper)
public class DbUtil extends SQLiteOpenHelper
{
public DbUtil(Context context) {
super(context, NAME_DB, null, 1);
// other init code here...
}
// onCreate and other override
}
在您进入活动的第一个onCreate方法只是做这样的事情:
In the first onCreate method of your entrance activity just do something like that:
Session.getInstance().initDBUtil(this);
,然后你可以使用吸气剂会话与访问DbUtil类:
and then you can use the getter in Session to access the DbUtil class with:
Session.getInstance().getUtil(). ... your method here ...
这篇关于如何访问我的SQLite数据库以静态的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!