Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger ApplicationComponent must be set

I need to expose my OkHttpClient from ApplicationModule so I added to ApplicationComponent. Something like this :

@Module
public class ApplicationModule {

    @Provides @Singleton
    public OkHttpClient provideOkHttpClient() {
    final OkHttpClient.Builder client = new OkHttpClient.Builder();

    return client.build();
}



@Singleton
@Component( modules = {ApplicationModule.class} )
public interface ApplicationComponent {

     OkHttpClient okHttpClient();

}

so I added the OkHttpClient okHttpClient(); in the ApplicationComponent as you can see right above.

Now in my NetworkModule I use it like :

@Module
public class NetworkModule {

    @Provides @ActivityScope
    public ProjectService provideProjectService(OkHttpClient client) {
          return new ProjectService(client);
}


  @Component( dependencies = {ApplicationComponent.class}, modules =   {NetworkModule.class} )
 @ActivityScope
 public interface NetworkComponent {

      void inject(@NonNull MyActivity myActivity);

}

but now when I get a runtime error :

Caused by: java.lang.IllegalStateException: css.test.demo.ApplicationComponent must be set
  at css.test.demo.main.projects.network.DaggerNetworkComponent$Builder.build(DaggerNetworkComponent.java:102)
  at css.test.demo.main.projects.MyActivity.onCreate(MyActivity.java:159)
  at android.app.Activity.performCreate(Activity.java:6237)

and here is how I build it in MyActivity :

NetworkComponent = DaggerNetworkComponent.builder()
    .NetworkModule(new NetworkModule(this))
    .build();

NetworkComponent.inject(this);
like image 967
mt0s Avatar asked May 28 '16 07:05

mt0s


1 Answers

I like to emphasize that dagger contains no magic—its is just plain java. If you don't give it the information it needs, the compiler will complain.

If you have a look at your DaggerNetworkComponent.Builder you will notice that it has a method called appComponent(AppComponent component). This is where dagger expects you to add the appcomponent that your NetworkComponent depends on.

NetworkComponent = DaggerNetworkComponent.builder()
        .NetworkModule(new NetworkModule(this))
        .appComponent(((App)getApplication()).getAppComponent()) // add your appComponent
        .build();

And it should work.

like image 193
David Medenjak Avatar answered Sep 22 '22 10:09

David Medenjak