Reputation: 2635
Below is the Activity, it is still using an old DI model, and i'm trying to migrate to Dagger2 (with dagger-android). I want to inject the Presenter, and as you can see, one dependency is the 'NewProjectDisplayer' which is a custom view in the activity.
This is the 'NewProjectDisplayer' which I want to provide to the Presenter
I have a Module (AppModule) which provides the global dependencies like ProjectService, LoginService etc..
Below is the NewProjectModule which I am having trouble with. One of the dependencies which is tied to the activity is the 'NewProjectDisplayer'. And I have no idea how I can provide it..
@Module
public class NewProjectActivityModule {
@Provides
NewProjectDisplayer provideNewProjectDisplayer(View view) {
// ??? return view.findViewById(R.id.create_project_view);
}
@Provides
NewProjectNavigator provideNewProjectNavigator(BaseActivity baseActivity) {
return new AndroidNewProjectNavigator(baseActivity);
}
@Provides
NewProjectPresenter provideNewProjectPresenter(NewProjectDisplayer displayer, //
ProjectService projectService,
LoginService loginService,
UserService userService,
NewProjectNavigator navigator, //
PermissionHandler permissionHandler,//
CropImageHandler cropImageHandler,//
RxSchedulers schedulers) {
return new NewProjectPresenter(displayer, projectService, loginService,
userService, navigator, permissionHandler, cropImageHandler, schedulers);
}
}
How can I provide this 'NewProjectDisplayer' so that the Presenter can be created and injected? I am using dagger-android.
Upvotes: 1
Views: 1283
Reputation: 315
You can't provide or do a findViewById
on an activity module that is compatible with dagger-android
, one reason being that the module is created before the view is actually on the hierarchy. Also, doing this is a not a good practice, but if you're still convinced you should do this, you could try creating a sub component that will have a module that provides the view dependency and it has to be created after setContentView
, as suggested by @elmorabea.
Upvotes: 2
Reputation: 3263
Just solving your problem, not sure if you should provide views with Dagger though.
Change your module to be something like that.
@Module
public class NewProjectActivityModule {
private View view;
public NewProjectActivityModule (View view) {
this.view = view;
}
@Provides
NewProjectDisplayer provideNewProjectDisplayer(View view) {
return view;
}
}
However, where ever you are creating your Dagger component you need to do something like that.
YourDaggerComponent.builder().newProjectActivityModule(new NewProjectActivityModule (yourViewInstance)).build();
Otherwise it will crash at run-time.
Upvotes: 0