如果我理解正确,在使用DB时,我必须执行以下操作 DaoMaster.OpenHelper helper = new DaoMaster.OpenHelper(this, "test-db", null) { @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }; SQLit
DaoMaster.OpenHelper helper = new DaoMaster.OpenHelper(this, "test-db", null) {
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
};
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
但是,如果我尝试在不扩展活动或服务的类中执行此操作,我只是无法通过其上下文.
什么是正确的方法来打开我的数据库?它应该在哪里完成?
如果你能提供除官方greendao之外的一些教程链接(我在那里找不到答案),那就太好了.
提供自定义应用程序对象并使用其上下文(因此Application Context).在AndroidManifest文件中,提供一个扩展Application的类.
<application android:label="@string/app_name"
android:name=".MyApp"
>
MyApp类看起来像这样:
public class MyApp extends Application {
private static MyApp instance;
public MyApp() {
instance = this;
}
public static MyApp getInstance() {
return instance;
}
....
所以现在,只要你的应用程序需要上下文,就可以调用MyApp.getInstance.只要在调用MyApp的onCreate之后调用它,您就会安全.请记住,实例是您的应用程序上下文,因此只要您的应用程序处于活动状态,它就会存活. (例如没有泄漏的危险)
new DaoMaster.OpenHelper(MyApp.getInstance(), "test-db", null)
