2016-07-06 53 views
0

我有這樣的模塊:Dagger2不注入字段

@Module 
public class MainModule { 

    private Context context; 

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

    @Provides 
    @Singleton 
    Dao providesDao() { 
     return new Dao(); 
    } 

    @Provides 
    @Singleton 
    FirstController providesFirstController(Dao dao) { 
     return new FirstController(dao); 
    } 

    @Provides 
    @Singleton 
    SecondController providesSecondController(Dao dao) { 
     return new SecondController(dao); 
    } 

} 

並且該組分:

@Singleton 
@Component(modules = MainModule.class) 
public interface MainComponent { 

    void inject(FirstView view); 

    void inject(SecondView view); 

} 

,最後,該噴射器類中,在App.onCreate()方法初始化:

public enum Injector { 

    INSTANCE; 

    MainComponent mainComponent; 

    public void initialize(App app) { 
     mainComponent = DaggerMainComponent.builder() 
       .mainModule(new MainModule(app)) 
       .build(); 
    } 

    public MainComponent getMainComponent() { 
     return mainComponent; 
    } 
} 

在我的FirstView和SecondView(即Fragment s)中,我有這個:

@Inject 
    FirstController controller; //and SecondController for the second view 

    @Override 
    public void onAttach(Context context) { 
     super.onAttach(context); 
     Injector.INSTANCE.getMainComponent().inject(this); 
    } 

在第一個片段中,一切正常,控制器被注入。但在第二種觀點中,它不是:僅返回null

我已經在「提供」模塊的方法中放置了斷點,並且執行了providesFirstController而不是providesSecondController

我在做什麼錯?我是Dagger2的新手,所以任何建議將不勝感激。

+0

你在哪裏調用'initialize(App app)'? – znat

+0

在'App.onCreate()'方法中。應用程序是我的類擴展應用程序 –

+0

在片段的構造函數調用'inject()' – EpicPandaForce

回答

0

解決!我有inject方法的簽名更改爲:

@Singleton 
@Component(modules = MainModule.class) 
public interface MainComponent { 

    void inject(FirstFragment view); 

    void inject(SecondFragment view); 

} 

我忘了說的firstView和SecondView是interface S,而不是類。注入方法需要具體的類。

0

如果這些是Fragments嘗試移動與注射連接的代碼:

Injector.INSTANCE.getMainComponent().inject(this); 

Fragmentpublic void onCreate(Bundle savedInstanceState)方法。 如果視圖在屏幕上不可見(同時添加FragmentManager),則可能不會調用方法。

+0

感謝您的答案。它仍然無法正常工作 –