Reputation: 43
I used dagger2 in my project, but the injection field is always null. Here is the code.
sorry, my english is poor. Thanks in advance.
Module
@Module
public class RetrofitModule {
@Provides
@Singleton
Retrofit provideRetrofit() {
return new Retrofit.Builder().build();
}
}
Component
@Component(modules = RetrofitModule.class)
public interface RetrofitComponent {
void inject(Activity activity);
}
And in MainActivity, I write this
DaggerRetrofitComponent.builder().build().inject(this);
But the Retrofit is always null. How can I solve it?
Upvotes: 2
Views: 1482
Reputation: 8852
You can not inject this way to your Activity class!
change your component like this and specify the exact name of your Activity:
@Component(modules = RetrofitModule.class)
public interface RetrofitComponent {
void inject(MainActivity activity);
}
and then perhaps also you have to change your module like this or anything else that fit your need:
@Module
public class RetrofitModule {
@Provides
Retrofit provideRetrofit() {
return new Retrofit.Builder().baseUrl("http://google.com").build();
}
}
By the way, make sure you have written @Inject before Retrofit declaration in your activity:
@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.
I hope it helps :)
Upvotes: 2