No injector was found for fragment dagger 2.11

In my case, My Fragment already extends DaggerFragment.
However, my Activity extends AppCompatActivity and I got error No injector was found for fragment dagger

It quite strange because the error is mention about Fragment and without using fragment, the Activity still work fine

Change Activity extends DaggerAppCompatActivity make it work


The problem with your code, is the incorrect implementation of the interface HasSupportFragmentInjector or HasFragmentInjector (it depends on whether you are using the support library for fragments or not).

You should implement this interface either in your Activity that is hosting the fragment, or in your Application class. Personally, I 'd recommend the following Application class so you don't bother implementing it on every Activity that hosts a Fragment:

public class MyApplication extends Application implements HasActivityInjector, HasSupportFragmentInjector {

    @Inject
    DispatchingAndroidInjector<Activity> mActivityInjector;

    @Inject
    DispatchingAndroidInjector<Fragment> mFragmentInjector;

    @Override
    public void onCreate() {
        super.onCreate();

        //The way you build your top-level Application component can vary. This is just an example
        DaggerApplicationComponent.builder()
            .application(this)
            .build()
            .inject(this);

    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return mActivityInjector;
    }

    @Override
    public AndroidInjector<Fragment> supportFragmentInjector() {
        return mFragmentInjector;
    }
}

And then in you inject your Fragments (as you already do in your code):

@Override
public void onAttach(Context context) {
    AndroidSupportInjection.inject(this);
    super.onAttach(context);
}

If the above is not working, make sure you have created the appropriate Components/Subcomponents for the screen you are trying to inject. If you are using @ContributesAndroidInjector instead of manually defining components, make sure you have one entry for your screen in your binding Module:

@ContributesAndroidInjector(modules = MyScreenModule.class) abstract MyScreenActivity bindMyScreen();

If you still can't get it to work. I recommend reading the actual Dagger documentation:

Hope it helps.

Tags:

Android