如果我理解正确的话,用DB工作时,我必须做如下
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();
但是,如果我尝试做这在没有扩大的活动或服务类,我只是couln't通过他们的背景。
什么是打开我的数据库正确的做法? 当它应该做些什么呢?
如果你能提供一些教程链接除了官方greendao(我无法找到答案了),这将是巨大的。
提供自定义应用程序对象,并使用它的上下文(这样的应用上下文)。
在AndroidManifest文件,提供了扩展应用程序的类。
<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
被调用时,你会很安全。 请记住, instance
是您的应用程序上下文所以这将是活着,只要你的应用程序是活的。 (例如,没有泄漏的危险)
new DaoMaster.OpenHelper(MyApp.getInstance(), "test-db", null)
你可以通过从具有它的类(活动或服务),以从中你要调用OpenHelper类的语境:
Public class NonActivity {
private Context context;
public NonActivity(Context context) {
this.context = context;
}
}
并使用它:
new OpenHelper(context, "test-db", null)