gpt4 book ai didi

android - Dagger 未在 Android 中初始化注入(inject)字段

转载 作者:行者123 更新时间:2023-11-29 21:09:26 27 4
gpt4 key购买 nike

开始将 Dagger 引入我的应用程序,但我在初始化一个非常基本的字段时遇到了问题。这是我的代码的简化版本:

@Inject public DaggerUtils daggerUtils; 

public class AppState extends Application {
@Override
public void onCreate() {
super.onCreate();

// Set up Dagger
AppModule appModule = new AppModule();
mObjectGraph.create(appModule);

daggerUtils.print();
}
}

使用的模块:

@Module(
injects = { AppState.class}
)
public class AppModule {

// This provides method is commented out because from what I can understand from the Dagger documentation
// Dagger should automatically take care of calling the constructor I have provided
// with the @Inject annotation. I have tried commenting this out as well and it still
// fails.
//@Provides
//DaggerUtils provideDaggerUtils() {
// return new DaggerUtils();
//}
}

基本实用类:

public class DaggerUtils {

@Inject
public DaggerUtils() {

}

public void print(){
Logger.e("Dagger", "printed instantiated");
}
}

所以据我了解,因为我在 DaggerUtils 构造函数之前有 @Inject 注释,在我的 AppState 类中使用的 DaggerUtils 实例之前有 @Inject 注释,Dagger 应该负责初始化 DaggerUtils 实例,而我不必调用构造函数。但是,当我尝试调用 daggerUtils.print() (AppState 类中的第 12 行)时,它一直给我一个 NullPointerException。为什么 Dagger 不初始化 DaggerUtils?我觉得我在这里缺少一些非常基本的东西。我还尝试使用 AppModule 中注释掉的 @Provides 方法来提供实例化的 DaggerUtils,但它仍然无法正常工作。

最佳答案

今晚我遇到了同样的问题。

对于每个需要注入(inject)的类,你必须调用:

mObjectGraph.create(appModule).inject(this);

这对于在应用程序中创建注入(inject)方法很有用。

public void inject(Object object) {
mObjectGraph.inject(object);
}

关于android - Dagger 未在 Android 中初始化注入(inject)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23436184/

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