I want to inject a singleton SqliteOpenHelper
in a ContentProvider
. However, it seems that the ContentProvider
instance is being built bef
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 exampleattachBaseContext
.
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.