Search code examples
androidapimoduledagger

Dagger Component is not sugested in my android studio and causing me building errors?


Hoping you are doing well, I am trying to create a simple CRUD using Retrofit, Dagger etc ..

I created my ApiComponent :

    @Component(modules = {ApiModule.class})
    public interface ContractApiComponent {

        public void inject(ContractsListViewModel contractListViewModel);
        public void inject(ContractService contractService);

    }

I rebuilded my project many times.

I tried after to call the Dagger Component in my Service but it is not been suggested:

    public class ContractService {

        public static ContractService instance;

        @Inject
        public ContractApi api;

        public ContractService(){
            DaggerContractApiComponent.create().inject(this);
        }
    }

This is my ApiModule :

@Module
public class ApiModule {

    public static String BASE_URL = "http://localhost/newconceptsphp";

    @Provides
    public ContractApi provideContractApi(){
        return new Retrofit.Builder().baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
                .create(ContractApi.class);
    }

}

I was typing Dagger, my DaggerContractApiCompnent has been suggested, it means it is known by the system, then I tried to run my project finally and suddenly it turned red, my dagger no longer known in my editor.

I am trying to rebuild and rebuild and nothing seems to solve the problem.

Any help would be much appreciated if you faced this before.


Solution

  • it is normal, you are missing a method in your ApiModule, returning the service with a Provides annotations.

    @Module public class ApiModule {

      public static String BASE_URL = "http://localhost/newconceptsphp";
    
      @Provides
      public ContractApi provideContractApi(){
        return new Retrofit.Builder().baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
                .create(ContractApi.class);
      }
    
      @Provides
      public ContractService provideContractService(){
        return ContractService.getInstance();
      }
    
     }
    

    Add it and I think it is gonna work.