2
votes

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?

1
Where do you call inject()? - Egor
MainActivity - onCreate() - Manchester Lee
It also looks like you're forgetting to pass the instance of RetrofitModule when creating the component, you should be calling .retrofitModule(new RetrofitModule()). - Egor
DaggerRetrofitComponent.builder().retrofitModule(new RetrofitModule()).build().inject(this); - Manchester Lee
Android studio tells me retrofitModule method is deprecated - Manchester Lee

1 Answers

2
votes

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 :)