Skip to content Skip to sidebar Skip to footer

How To Inject Dependencies Into Any Kind Of Object With Dagger2?

According to http://konmik.github.io/snorkeling-with-dagger-2.html i could just add inject(Anything anything) into AppComponent.java, but this doesn't work for me, in the article

Solution 1:

Inject child fragments instead of BaseFragment. In your case:

public class ListFragment extends BaseFragment {

    @Inject ListFragmentPresenterImpl listFragmentPresenter;

    public static ListFragment newInstance(){
        ListFragment result = new ListFragment();
        return result;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((MainActivity)getActivity()).getComponent().injectFragment(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View rootView = inflater.inflate(R.layout.list_fragment, container, false);
        Log.d("",listFragmentPresenter.sayHello());  // NPE HERE
        return rootView;
    }
}

And in your Component class:

@AScope
@Component(dependencies = ApplicationComponent.class,
           modules = ActivityModule.class)
interface ActivityComponent {
    void injectActivity(MainActivity activity);
    void injectFragment(ListFragment fragment);
    // Put any more injects here, if BaseFragment has
    // any other children that need to be injected, for example:
    void inject(MapFragment fragment);
    void inject(DetailFragment fragment);
}

Parent -> Child injection is not working in Dagger 2. It was covered here, here and this SO question.


Post a Comment for "How To Inject Dependencies Into Any Kind Of Object With Dagger2?"