I've got a simple Dagger 2 test-setup, based on http://konmik.github.io/snorkeling-with-dagger-2.html. It injects a PreferenceLogger which outputs all the preferences. In the injected class, I can @Inject more classes.
public class MainActivity extends Activity {
@Inject PreferencesLogger logger;
@Inject MainPresenter presenter;
@Override protected void onCreate(Bundle savedInstanceState) {
MyApplication.getComponent().inject(this);
presenter.doStuff();
logger.log(this);
}
}
public class PreferencesLogger {
@Inject OkHttpClient client;
@Inject public PreferencesLogger() {}
public void log(Contect context) {
// this.client is available
}
}
When I run this, logger is set, and inside PreferencesLogger.log the OkHttpClient is correctly set. So this example works as expected. Now I'm trying to get a MVP structure in place. There's a MainPresenter interface with an implementation. In the MainActivity I set an:
@Inject MainPresenter presenter;
so I could switch this MainPresenter with an alternative (debug or test) implementation. Ofcourse, now I need a Module to specify what implementation I want to use.
public interface MainPresenter {
void doStuff();
}
public class MainPresenterImpl implements MainPresenter {
@Inject OkHttpClient client;
public MainPresenterImpl() {}
@Override public void doStuff() {
// this.client is not available
}
}
@Module public class MainActivityModule {
@Provides MainPresenter provideMainPresenter() {
return new MainPresenterImpl();
}
}
A problem now occurs that the OkHttpClient isn't injected anymore. Ofcourse I could alter the Module to accept a parameter OkHttpClient, but I don't think this is the suggested way to do it. Is there a reason why the MainPresenterImpl doesn't Inject correctly?