Dagger 2错误:如果没有@Providers注释方法,则无法提供android.content.Context
我正在我的项目中实施Dagger2。为此,我编写了以下代码行:Dagger 2错误:如果没有@Providers注释方法,则无法提供android.content.Context,android,dagger-2,Android,Dagger 2,我正在我的项目中实施Dagger2。为此,我编写了以下代码行: @Inject VideoControllerView mediaController; @Module public class PlayerModule { @Provides VideoControllerView providesVideoControllerView(Context context, VideoControllerView.Controlers cntrls) { ret
@Inject
VideoControllerView mediaController;
@Module
public class PlayerModule {
@Provides
VideoControllerView providesVideoControllerView(Context context, VideoControllerView.Controlers cntrls) {
return new VideoControllerView(context, cntrls);
}
}
@Component(modules = PlayerModule.class)
public interface PlayerComponent {
VideoControllerView getVideoControllerView();
}
但当我试图编译我的应用程序时,我得到了以下给定错误:
Error:(14, 25) error: android.content.Context cannot be provided without an @Provides-annotated method.
android.content.Context is injected at
com.multitv.multitvplayersdk.module.PlayerModule.providesVideoControllerView(context, …)
com.multitv.multitvplayersdk.controls.VideoControllerView is provided at
com.multitv.multitvplayersdk.component.PlayerComponent.getVideoControllerView()
我环顾了一下如何解决这个问题,但没有结果。请帮助我。请尝试理解错误
PlayerModule.providesVideoControllerView(context,…)
需要一个上下文,但Dagger无法访问任何context
对象,因此它无法传入任何上下文。因此,它会创建错误,告诉您它找不到任何上下文
,您应该为它添加这样做的方法
如果没有@Providers注释方法,则无法提供上下文
因此,上下文
不能在没有@提供
-注释方法的情况下提供
确保PlayerModule
所属的组件具有访问上下文的权限
要么将其作为应用程序组件的子组件,要么将上下文添加到PlayerModule
,要么将活动实例绑定为上下文,等等
有很多方法可以做到这一点,但最终您需要在其中一个模块中使用如下方法:
@Provides Context provideContext() { return myContext; }
一旦Dagger可以找到上下文
错误就会消失。您需要如下模块:
@Module
public class ContextModule {
private Context context;
public ContextModule(Context context) {
this.context = context;
}
@Provides
@UefaApplicationScope
Context provideContext() {
return context;
}
}
然后方法注入:
@Provides
@Inject
VideoControllerView providesVideoControllerView(Context context, VideoControllerView.Controlers cntrls) {
return new VideoControllerView(context, cntrls);
}
选中它显示代码,在那里创建PlayerComponent
。只有在正确编译之后,我才能找到DaggerPlayerComponent。此时此刻,工作室甚至不允许我编译解决我的问题。谢谢你