Inject database in a ContentProvider with dagger

前端 未结 5 2674
无人及你
无人及你 2021-02-19 22:57

I want to inject a singleton SqliteOpenHelper in a ContentProvider. However, it seems that the ContentProvider instance is being built bef

5条回答
  •  轮回少年
    2021-02-19 23:15

    Simple Solution

    There is a simple reason for this, onCreate() provider is called before the appropriate method in the Application. You can make the creation of a component in another method of the Application, for example attachBaseContext.


    1 Move your logic from onCreate to attachBaseContext in your Application.

    @Override
    public void attachBaseContext(Context base){
    
        super.attachBaseContext(base);
    
        mApplicationComponent = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this))
                .build();
        mApplicationComponent.inject(this);
    }
    

    2 You can now inject in OnCreate in your ContentProvider:

    public boolean onCreate() {
    
        YourMainApplication.get(getContext()).getComponent().inject(this);
    
        return true;
    }
    

    Disclaimer: Full Credits to @LeEnot from this russian blog: Dagger2 Inject in Content Provider. The answer is listed here for convenience as it is not available in English.

提交回复
热议问题