Pass Context or Activity to adapter using Dagger 2

2019-08-08 07:07发布

问题:

I inject an Adapter using Dagger 2 without context and it is working, but I am not able to do when I am passing context parameter. Error is coming like this

error: android.content.Context cannot be provided without an @Provides-annotated method.

Dagger Component

@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = MainFragmentModule.class)
public interface MainFragmentComponent {

    void inject(MainFragment mainFragment);

    @ActivityContext
    Context provideContext();
}

Fragment Module

@Module
public class MainFragmentModule {

    private MainFragmentContract.View mView;
    private Activity mActivity;
    Context mContext;

    MainFragmentModule(MainFragmentContract.View view, Context context) {
        mView = view;
        mContext = context;
    }

    @Provides
    MainFragmentContract.View providesView() {
        return mView;
    }

    @Provides
    @ActivityContext
    Context provideContext() {
        return mContext;
    }


}

Adapter

  @Inject
    public ConversationAdapter(MainFragmentPresenter mainPresenter, Context context) {
        mMainFragmentPresenter = mainPresenter;
        mContext =context;
    }

回答1:

You have told dagger, that you are providing a specific context:

@ActivityContext
Context provideContext();

And then you are asking dagger to inject your adapter with another type of context - one, which is not annotated with @ActivityContext.

Instead, you should explicitly define, that you are willing to provide exactly that type of context:


    @Inject
    public ConversationAdapter(..., @ActivityContext Context context) {
        ...
    }