In this class which @Override method i should use and what will be the code to add dependency in fragment?
The correct place to call injection inside a Fragment is onAttach(Context context)
. This is stated in the where to inject section of the Dagger 2 user guide here
@Override
public void onAttach(Context context) {
((AppController) context.getApplicationContext()).getNetComponent().inject(this);
super.onAttach(context);
}
The correct place to call injection inside a Service is onCreate()
@Override
public void onCreate() {
((AppController) getApplication()).getNetComponent().inject(this);
super.onCreate();
}
Note that in both cases the request for injection comes before the call to super.onCreate()
. The Dagger user guide explains it like this:
It is crucial to call AndroidInjection.inject() before super.onCreate() in an Activity, since the call to super attaches Fragments from the previous activity instance during configuration change, which in turn injects the Fragments. In order for the Fragment injection to succeed, the Activity must already be injected. For users of ErrorProne, it is a compiler error to call AndroidInjection.inject() after super.onCreate().
In other words:
- The Activity
super.onCreate()
call re-attaches Fragments from a previous instance
- This
super
call in cause Fragments to be re-injected (since Fragments are injected in onAttach
)
- Fragments should be injected after their Activity is injected, therefore request injection in your Activity before calling
super.onCreate()
.
You can always check where to inject by looking at the relevant source code for the com.google.dagger:dagger-android
classes like DaggerFragment
and DaggerService
. See the GitHub repo here
For your specific example, please make sure you have added the new injection sites to the NetComponent:
void inject(FragmentBrandList frag);
void inject(BrandListService service);