dagger2 注入字段 NullPointerException

dagger2 Inject field NullPointerException

我在我的项目中使用了dagger2,但注入字段始终为空。这是代码。

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 始终为空。我该如何解决?

你不能以这种方式注入你的 Activity class!

像这样更改您的组件并指定您的组件的确切名称 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.

希望对您有所帮助:)