gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:22:09 25 4
gpt4 key购买 nike

我想在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com