Dagger 2错误:如果没有@ Provide-annotated方法,则无法提供android.content.Context

Nas*_*ran 10 android dagger-2

我正在我的项目中实施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();
}
Run Code Online (Sandbox Code Playgroud)

但是当我试图编译我的应用程序时,我得到的错误是:

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()
Run Code Online (Sandbox Code Playgroud)

我已经四处查看如何解决这个问题,但无济于事.请帮我.

Dav*_*jak 9

请尝试了解错误.

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

如果没有@ Provide-annotated方法,则无法提供上下文.

因此...... context如果没有@Provides注释方法,则无法提供A.


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

将其作为ApplicationComponent的子组件,向您添加Context PlayerModule,将Activity实例绑定为Context等

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

@Provides Context provideContext() { return myContext; }
Run Code Online (Sandbox Code Playgroud)

一旦Dagger找到Context错误就会消失.


Spy*_*Zip 5

你需要像这样的模块:

@Module
public class ContextModule {

    private Context context;

    public ContextModule(Context context) {
        this.context = context;
    }

    @Provides
    @UefaApplicationScope
    Context provideContext() {
        return context;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后方法注入:

    @Provides
    @Inject
    VideoControllerView providesVideoControllerView(Context context, VideoControllerView.Controlers cntrls) {
        return new VideoControllerView(context, cntrls);
    }
Run Code Online (Sandbox Code Playgroud)