I have a module FragmentModule
@Module
public class FragmentModule
{
@Provides
public static PickerDashboardFragment providesPickerDashboard(int status, String name, Object someComplexObject)
{
PickerDashboardFragment fragment = new PickerDashboardFragment();
Bundle b = new Bundle();
b.putInt("status", status);
b.putString("name", name);
b.putInt("object", someComplexObject);
fragment.setArguments(bundle);
return fragment;
}
@Provides
public static PickingFragment providesPickingFragment()
{
PickingFragment fragment = new PickingFragment();
return fragment;
}
}
Here's my Component class
@Component(modules = {UtilModule.class, FragmentModule.class})
public interface ApplicationComponent
{
void inject(PickerDashboardActivity target);
}
In my activity this is how i'm injecting the PickerDashboardActivity
@Inject
PickerDashboardFragment frag;
ApplicationComponent component = DaggerApplicationComponent.builder().build();
component.inject(this);
My question is what's the best and easiest way to provide the dependencies for PickerDashboardFragment providesPickerDashboard(int status, String name, Object someComplexObject)
i.e status, name and someComplexObject.
Best Regards
Don't inject Fragments into your Activities using Dagger 2. Why? Fragments have a lifecycle controlled by the Android OS. When you add a Fragment to an Activity using a transaction, the FragmentManager will retain a reference to the Fragment. When the Activity
instanceState
is saved, the Fragments added to FragmentManager will be saved. When the Activity is restored, if you request injection without checking for the presence of the Fragment in the FragmentManager, your Activity begin to reference two instances of the Fragment and create a memory leak.For this reason, in
void onCreate(Bundle savedInstanceState)
method you should check for the presence of the retained Fragment in the FragmentManager rather than request injection from Dagger 2. If the Fragment is not retained then you can instantiate it at that point. It is perfectly fine to use thenew
keyword or static factories for this.Example:
However, at another level it seems you are asking how to combine parameters and dependencies. A good solution for these is often Factories. Say you have a CoffeeMaker:
The beanFlavour is variable (dark, roasted etc.) and varies and so is more like a parameter than a dependency. You could then write a CoffeeMakerFactory and inject this using Dagger 2:
Factories are the standard solution for a combination of dependency and parameters see here and they can even be be generated using code generation tools like Google Auto.
Add attributes and
Provides
methods to your module like this:Having a module providing ints and Strings will probably make you use some qualifiers (such as
Named
) in order to avoid collisions