我在项目中使用了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始终为null。怎么解决呢?
最佳答案
你不能以这种方式注入(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/