Passing correct context to greendao's OpenHelper constructor

徘徊边缘 提交于 2019-12-06 07:32:51

问题


If I understand correctly, when working with DB, I have to do as follows

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();

But if I try to do this in classes that aren't extending activity or service, I simply couln't pass their context.

What is right approach to open my DB? Where should it be done?

If you can provide some tutorial links besides official greendao (I couldn't find the answer there), it would be great.


回答1:


provide custom application object and use its context (so Application Context).

in your AndroidManifest file, provide a class that extends Application.

<application android:label="@string/app_name"
             android:name=".MyApp"
             >

MyApp class looks like this:

public class MyApp extends Application {

    private static MyApp instance;
    public MyApp() {
        instance = this;
    }

    public static MyApp getInstance() {
        return instance;
    }
....

so now whenever you need context in your app, you can call MyApp.getInstance. As long as you call it after MyApp's onCreate is called, you will be safe. Keep in mind that instance is your application context so it will be alive as long as your app is alive. (e.g. no danger of leaking)

new DaoMaster.OpenHelper(MyApp.getInstance(), "test-db", null)



回答2:


You can pass the Context from the class which has it (Activity or Service) to a class from which you going to call the OpenHelper:

Public class NonActivity {
 private Context context;

   public NonActivity(Context context) {
       this.context = context;
    }
}

and use it:

new OpenHelper(context, "test-db", null).



来源:https://stackoverflow.com/questions/14424099/passing-correct-context-to-greendaos-openhelper-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!