【问题标题】:Dagger 2 error: android.content.Context cannot be provided without an @Provides-annotated methodDagger 2 错误:没有@Provides-annotated 方法无法提供android.content.Context
【发布时间】:2017-11-05 21:17:52
【问题描述】:

我正在我的项目中实现 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()

我已经查看了如何解决此问题,但无济于事。请帮帮我。

【问题讨论】:

标签: android dagger-2


【解决方案1】:

请尝试理解错误。

PlayerModule.providesVideoControllerView(context, …) 需要上下文,但 Dagger 无法访问任何 Context 对象,因此它无法传入任何 Context。因此它会产生错误,告诉您它找不到任何Context,并且您应该为其添加一种方法。

没有@Provides-annotated 方法就不能提供上下文。

因此...如果没有@Provides-annotated 方法,就无法提供context


确保您的PlayerModule 所属的组件可以访问上下文。

要么将其设为 ApplicationComponent 的子组件,要么将 Context 添加到 PlayerModule,将 Activity 实例绑定为 Context,等等

有很多方法可以做到这一点,但最后你需要在你的一个模块中使用如下方法:

@Provides Context provideContext() { return myContext; }

一旦 Dagger 可以找到 Context,错误就会消失。

【讨论】:

  • 解决了我的问题。谢谢你
【解决方案2】:

你需要这样的模块:

@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);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    相关资源
    最近更新 更多