ApplicationComponent dagger must be installed

I need to set my OkHttpClientout ApplicationModule, so I added in ApplicationComponent. Something like that:

@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 OkHttpClient okHttpClient();in ApplicationComponent, as you can see right above.

Now in mine NetworkModuleI use it as:

@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 the 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 this is how I create it in MyActivity:

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

NetworkComponent.inject(this);
+4
source share
1 answer

I like to emphasize that the dagger does not contain magic - it's just java. If you do not give him the necessary information, the compiler will complain.

DaggerNetworkComponent.Builder, , appComponent(AppComponent component). , app, NetworkComponent.

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

.

+15

All Articles