android - 用 Dagger 在 ContentProvider 中注入(inject)数据库

标签 android dagger

我想在 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 example attachBaseContext.


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/

相关文章:

android - ORMLite 中的集合

android - 哪个是移动应用程序开发的最佳跨平台框架?

square - Android 中的 Dagger 作用域

Android Dagger 并在任意时刻设置模块

android - 事件总线 fragment 注销

android - 如何检查edittext的文本是否为电子邮件地址?

dagger-2 - 在 Dagger 中,一个 Inject 注释类是否也可以作为提供者?

android - 如何使用 Otto 回调 onAttach 中的 Activity?

java - 我可以使用 Dagger 的某种辅助注入(inject)吗?

android - 在 TabActivity 和它的子 Activities 之间交换数据。可能的?