0

When I compile my Android project, I catch such error:

Error:(15, 13) error: android.content.Context cannot be provided without an @Provides-annotated method. android.content.Context is provided at com......di.components.AppComponent.getContext()

My component:

@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {
    Context getContext();
    DataManager getDataManager();
}

My module:

@Module
public class AppModule {
    protected final Application mApplication;

    public AppModule(Application application) {
        mApplication = application;
    }

    @Provides
    @Singleton
    Application provideApplication() {
        return mApplication;
    }

    @Provides
    @ApplicationContext
    @Singleton
    Context provideContext() {
        return mApplication;
    }

    @Provides
    @Singleton
    DataManager provideDataManager() {
        return new DataManager();
    }
}
David Medenjak
  • 33,993
  • 14
  • 106
  • 134
asf
  • 355
  • 1
  • 3
  • 17
  • you have `ApplicationContext` annotation in module, it should be removed, since you already have `Singleton` scope annotation – nikis Jun 22 '17 at 18:16
  • This link https://stackoverflow.com/questions/30552481/context-cannot-be-provided-without-an-provides-annotated-method-but-it-is might be of help – nbokmans Jun 22 '17 at 18:16

1 Answers1

2

Your component says it can provide a Context:

@Singleton
@Component(modules = {AppModule.class})
interface AppComponent {
  Context getContext();
}

When all it knows about is a @ApplicationContext Context (notice the qualifier?):

@Module
class AppModule {

  @Provides
  @Singleton
  @ApplicationContext
  Context provideContext() {
    return mApplication;
  }
}

You can either remove the @ApplicationContext qualifier and just provide a Context from your module, which could get in the way if you try to also provide your activities context, or you keep your qualifier and actually provide the qualified context:

@Singleton
@Component(modules = {AppModule.class})
interface AppComponent {
  @ApplicationContext
  Context getContext();
}

If you try to use / inject the application context you will also need to use the qualifier:

@ApplicationContext @Inject Context mContext;
David Medenjak
  • 33,993
  • 14
  • 106
  • 134