質問

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.

役に立ちましたか?

解決

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)

他のヒント

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).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top