Pass Context or Activity to adapter using Dagger 2

假如想象 提交于 2019-12-13 17:42:59

问题


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) {
        ...
    }



来源:https://stackoverflow.com/questions/45479621/pass-context-or-activity-to-adapter-using-dagger-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!