gpt4 book ai didi

android - dagger2 注入(inject)字段 NullPointerException

转载 作者:搜寻专家 更新时间:2023-11-01 09:40:48 25 4
gpt4 key购买 nike

我在我的项目中使用了dagger2,但是注入(inject)字段总是空的。这是代码。

sorry, my english is poor. Thanks in advance.

模块

@Module
public class RetrofitModule {

@Provides
@Singleton
Retrofit provideRetrofit() {
return new Retrofit.Builder().build();
}
}

组件

@Component(modules = RetrofitModule.class)
public interface RetrofitComponent {

void inject(Activity activity);

}

然后在 MainActivity 中,我这样写

DaggerRetrofitComponent.builder().build().inject(this);

但 Retrofit 始终为空。我该如何解决?

最佳答案

你不能以这种方式注入(inject)你的 Activity 类!

像这样更改您的组件并指定您的 Activity 的确切名称:

@Component(modules = RetrofitModule.class)
public interface RetrofitComponent {

void inject(MainActivity activity);

}

然后也许您还必须像这样更改您的模块或满足您需要的任何其他内容:

@Module
public class RetrofitModule {

@Provides
Retrofit provideRetrofit() {
return new Retrofit.Builder().baseUrl("http://google.com").build();
}
}

顺便说一下,确保你在 Activity 中的 Retrofit 声明之前写了@Inject:

@Inject
Retrofit retrofit;

note that: if you want to have singleton provide in your module, the whole component cannot remain unstopped and it must be annotated @Singleton.

希望对你有帮助:)

关于android - dagger2 注入(inject)字段 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39980666/

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