简体   繁体   中英

Dagger2 is not injecting field

I have this module:

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

}

and this component:

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

    void inject(FirstView view);

    void inject(SecondView view);

}

and, finally, the injector class, that is initialized in App.onCreate() method:

public enum Injector {

    INSTANCE;

    MainComponent mainComponent;

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

    public MainComponent getMainComponent() {
        return mainComponent;
    }
}

In my FirstView and SecondView (that are Fragment s), I have this:

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

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

In the first fragment, everything is ok, the controller is injected. But in the second view it is not: just returning null .

I have put breakpoints in "provides" module's methods and the providesFirstController is executed but not the providesSecondController .

What am I doing wrong? I'm new in Dagger2 so any advice will be appreciated.

If those are Fragments try moving the code connected with injecting:

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

to the Fragment 's public void onCreate(Bundle savedInstanceState) method. If the views are not visible on the screen at the same time (added by FragmentManager ), then the SecondView onAttach method may not be called.

Solved! I have change the signature of inject methods to:

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

    void inject(FirstFragment view);

    void inject(SecondFragment view);

}

I forget to say that FirstView and SecondView are interface s, not classes. And inject methods need the concrete class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM