2017-06-05 113 views
1

我正在實施匕首2在我的項目中。對於這一點,我已經寫了下面的代碼行:Dagger 2錯誤:android.content.Context無法提供@提供註釋的方法

@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() 

我已經環顧四周,就如何解決這個問題,但無濟於事。請幫幫我。

+0

檢查https://stackoverflow.com/questions/30692501/dagger-2-injecting-android-context –

+0

顯示代碼,在其中創建'PlayerComponent'。 – azizbekian

+0

只有編譯完成後,我才能找到DaggerPlayerComponent。在這個時候,工作室甚至不允許我編譯 –

回答

2

請嘗試瞭解錯誤。

PlayerModule.providesVideoControllerView(context, …)需要一個上下文,但Dagger不能訪問任何Context對象,所以它不能通過任何Context。它因此產生了錯誤,告訴你它找不到任何Context,並且你應該添加一個方法讓它這樣做。

Context cannot be provided without an @Provides-annotated method.

因此...不能沒有@Provides -annotated方法可以提供context


確保您的PlayerModule是可以訪問上下文的組件。

要麼讓它成爲你ApplicationComponent的子組件,上下文添加到您的PlayerModule,你的活動實例綁定的語境等

有很多方法可以做到這一點,但最後你需要的方法就像在你的模塊中的以下內容:

@Provides Context provideContext() { return myContext; } 

一旦匕首可以找到一個Context錯誤就會消失。

0

你需要像模塊:

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