Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Fragment and Dependency Injection

as the title says, I'm trying to figure out which one is the best way to inject a dependency in a Fragment. I want to be independent from external frameworks like RoboGuice etc.

Now, in the simplest way possible, I have an interface that abstracts some kind of logic, and, from an Activity, I want to inject an implementation of this interface. I know that I have to provide a default constructor for my fragment, since the system might need to recreate the fragment at some point, and that the usual way to create a new instance of the fragment is to provide static method that handles the creation like this:

public static Fragment newInstance() {
    final Bundle bundle = new Bundle();
    ...
    final Fragment fragment = new MyFragment();
    fragment.setArguments(bundle);
    return fragment;
}

How can I pass my dependency to the fragment? Should I make it implement the Parcelable or Serializable interfaces and then pack it in the Bundle? Is there some other way to achieve the result?

like image 788
TheImplementer Avatar asked Apr 29 '14 21:04

TheImplementer


1 Answers

A simple solution is to declare an interface which is declaring the Dependencies required for the Fragment. Then let the Context of the Fragment implement this interface, and poll the dependencies when needed from the Context.

Contract:

public interface MyDependencies {

    MyDep getDep();

}

Activity:

public MyActivity extends Activity implements MyDependencies {

    @Override
    public MyDep getDep(){
       return createMyDependencyOrGetItFromASingletonOrGetItFromApplication()
    }
}

Fragment:

public void onActivityCreated(Bundle b){
     super.onActivityCreated(b)

     if (getActivity() instanceOf MyDependencies) {
         MyDep dep = ((MyDependencies) getActivity).getDep();
     } else {
         throw new RuntimeException("Context does not support the Fragment, implement MyDependencies")
     }
}

So, in fact, there is no unnecessary coupling to the Activity because the contract is defined by an interface.

like image 137
joecks Avatar answered Oct 21 '22 03:10

joecks