Ray Wendelich Dagger Tutorial
- Add
inject()
inAppComponent
withFoodzActivity
argument.
@Singleton @Component(modules = {AppModule.class, PresenterModule.class})
public interface AppComponent {
void inject(FoodzActivity target);
}
- Add
provideFoodzPresenter()
inPresenterModule
.
@Module
public class PresenterModule {
@Provides @Singleton
FoodzPresenter provideFoodzPresenter() { return new FoodzPresenterImpl(); }
}
- Add
@Inject
annotation toFoodzPresenter presenter
inFoodzActivity
.
public class FoodzActivity extends LifecycleLoggingActivity implements FoodzView {
// FoodzPresenter presenter;
@Inject FoodzPresenter presenter
...
@Override protected void onCreate(Bundle savedInstanceState) {
...
// presenter = new FoodzPresenterImpl();
- Add
DeezFoodzApplication.getAppComponent().inject(this)
inonCreate()
inFoodzActivity
public class FoodzActivity extends LifecycleLoggingActivity implements FoodzView {
@Override protected void onCreate(Bundle savedInstanceState) {
...
setContentView(R.layout.activity_foodz);
((DeezFoodzApplication)getApplication()).getAppComponent().inject(this);
ButterKnife.bind(this);
....
@Module
public class NetworkModule {
private static final String NAME_BASE_URL = "NAME_BASE_URL";
@Provides @Named(NAME_BASE_URL)
String provideBaseUrlString() { return Constants.BASE_URL; }
@Provides @Singleton
Converter.Factory provideGsonConverter() { return GsonConverterFactory.create(); }
@Provides @Singleton
Retrofit provideRetroFit(Converter.Factory converter, @Named(NAME_BASE_URL) String baseUrl) {
return new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(converter)
.build();
}
@Provides @Singleton
UsdaApi provideUsdaApi(Retrofit retrofit) { return retrofit.create(UsdaApi.class); }
}
- Add
NetworkModule
toAppComponent
withFood(z)PresenterImpl
arguments:
@Singleton @Component(modules = {AppModule.class, PresenterModule.class, NetworkModule.class})
public interface AppComponent {
...
void inject(FoodzPresenterImpl target);
void inject(FoodPresenterImpl target);
}
- Modify
PresenterModule
so that it passes context as parameter:
@Module
public class PresenterModule {
@Provides @Singleton
FoodzPresenter provideFoodzPresenter(Context context) { return new FoodzPresenterImpl(context); }
FoodPresenter provideFoodPresenter(Context context) { return new FoodPresenterImpl(context); }
- Add
@Inject
annotation toUsdaApi
inFoodPresenterImpl
.
public class FoodzPresenterImpl implements FoodzPresenter {
...
@Inject UsdaApi usdaApi;
public FoodzPresenterImpl(Context context) { ((DeezFoodzApplication)context).getAppComponent().inject(this); }
...
@Override public void getFoodz() {
view.showLoading();
// Converter.Factory converter = GsonConverterFactory.create();
//
// Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(Constants.BASE_URL)
// .addConverterFactory(converter)
// .build();
//
// UsdaApi usdaApi = retrofit.create(UsdaApi.class);
usdaApi.getFoodzList().enqueue(new Callback<FoodzListResponse>() {
...