我想在 ContentProvider
中注入(inject)一个单例 SqliteOpenHelper
。但是,似乎在创建 Application 实例之前构建了 ContentProvider
实例(getApplicationContext()
返回 null)。什么时候可以注入(inject)数据库?我已经在 ContentProvider
的构造函数和 onCreate()
方法中进行了尝试。
最佳答案
简单的解决方案
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 在您的应用程序中将您的逻辑从 onCreate
移至 attachBaseContext
。
@Override
public void attachBaseContext(Context base){
super.attachBaseContext(base);
mApplicationComponent = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
mApplicationComponent.inject(this);
}
2 您现在可以在 ContentProvider 的 OnCreate
中注入(inject)
:
public boolean onCreate() {
YourMainApplication.get(getContext()).getComponent().inject(this);
return true;
}
免责声明: 来自这个俄罗斯博客的@LeEnot 的全部学分:Dagger2 Inject in Content Provider .为方便起见,在此列出答案,因为它没有英文版本。
关于android - 用 Dagger 在 ContentProvider 中注入(inject)数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23521083/