作者:文竹 | 来源:互联网 | 2023-02-02 10:05
如何解决《Dagger2错误:如果没有@Provide-annotated方法,则无法提供android.content.Context》经验,为你挑选了1个好方法。
我正在我的项目中实施dagger 2.为此,我写了下面的代码行:
@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()
我已经四处查看如何解决这个问题,但无济于事.请帮我.
1> David Medenj..:
请尝试了解错误.
PlayerModule.providesVideoControllerView(context, …)
需要一个上下文,但Dagger无法访问任何Context
对象,因此它无法传递任何对象Context
.因此它会创建错误,告诉您它找不到任何错误,Context
并且您应该为它添加一种方法.
如果没有@ Provide-annotated方法,则无法提供上下文.
因此...... context
如果没有@Provides
注释方法,则无法提供A.
确保您所属的组件可以PlayerModule
访问上下文.
将其作为ApplicationComponent的子组件,向您添加Context PlayerModule
,将Activity实例绑定为Context等
有很多方法可以做到这一点,但最终你需要在你的一个模块中使用如下方法:
@Provides Context provideContext() { return myContext; }
一旦Dagger找到Context
错误就会消失.