2017-02-16 37 views
0

對不起,我的英語,現在我開始學習dagger2,我不能明白爲什麼我有錯誤:匕首2離不開一個構造函數提供

Error:(9, 10) error: test.dagger.dagger.modules.MainActivityPresenterModule cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method. test.dagger.dagger.modules.MainActivityPresenterModule is injected at test.dagger.view.activitys.MainActivity.mainActivityPresenterModule test.dagger.view.activitys.MainActivity is injected at test.dagger.dagger.components.AppComponent.injectMainActivity(mainActivity)

應用

public class App extends Application { 

    private static AppComponent component; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     component = DaggerAppComponent.create(); 
    } 

    public static AppComponent getComponent() { 
     return component; 
    } 

} 

AppComponent

@Component(modules = {MainActivityPresenterModule.class}) 
public interface AppComponent { 
    void injectMainActivity(MainActivity mainActivity); 
} 

MainActivityPresenterModule

@Module 
public class MainActivityPresenterModule { 

    @Provides 
    MainActivityPresenter provideActivityPresenter(NetworkUtils networkUtils) { 
     return new MainActivityPresenter(networkUtils); 
    } 

    @Provides 
    NetworkUtils provideNetworkUtils(){ 
     return new NetworkUtils(); 
    } 


} 

NetworkUtils

public class NetworkUtils { 

    public boolean isConnection() { 
     return true; 
    } 

} 

MainActivityPresenter

public class MainActivityPresenter { 

    NetworkUtils networkUtils; 

    public MainActivityPresenter(NetworkUtils networkUtils) { 
     this.networkUtils = networkUtils; 
    } 

    public void getUser(){ 
     if(networkUtils.isConnection()) { 
      Log.e("getUser", "getUser"); 
     } else { 
      Log.e("no internet", "no internet connection"); 
     } 
    } 

} 

MainActivity

public class MainActivity extends AppCompatActivity { 


    @Inject 
    MainActivityPresenterModule mainActivityPresenterModule; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     App.getComponent().injectMainActivity(MainActivity.this); 


    } 
} 

回答

2

你可以注入僅與@Module(僅與@Provides註釋該模塊內的方法)註解的類所提供的東西。所以,你可以做@Inject MainActivityPresenter presenter,例如,不要試圖注入整個模塊,就像你試圖做的那樣。模塊應該匕首初始化註冊,像這樣(在應用#的onCreate)

component = DaggerAppComponent.builder() 
    .mainActivityPresenterModule(MainActivityPresenterModule()) 
    .build() 

在MainActivity你只需要調用注入到能夠注入的模塊中定義您的@Inject MainActivityPresenter presenter或任何其他內噴射,就像這樣:

@Inject MainActivityPresenter presenter  

override fun onCreate(savedInstanceState: Bundle) { 
    super.onCreate(savedInstanceState) 
    (application as App).component.inject(this) 

    // after #inject(this) above you can start using your injections: 

    presenter.getUser() 
} 

對不起,我寫的代碼片段在科特林因爲它編寫的方式是要少得多,希望你得到它的外觀在Java中的想法。

相關問題