Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Providing Injection for AndroidX Fragment with Dagger2?

I'm having some issues trying to provide an Injection to an AndroidX fragment, and I'm not sure what the exact issue is, and how to fix it. The app refuses to build, giving the following error:

 error: [Dagger/MissingBinding] java.util.Map<java.lang.Class<? extends androidx.fragment.app.Fragment>,javax.inject.Provider<dagger.android.AndroidInjector.Factory<? extends androidx.fragment.app.Fragment>>> cannot be provided without an @Provides-annotated method.

Here's the method to provide the Injection in the Fragment:

private fun performDependencyInjection() = AndroidSupportInjection.inject(this)

The fragment's parent Activity implements HasSupportFragmentInjector:

class MainActivity : BaseActivity(), MainMVPView, HasSupportFragmentInjector {
    @Inject
    internal lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
    ... 
    override fun supportFragmentInjector() = dispatchingAndroidInjector
}

I'm completely lost as to where to solve this error from here. It doesn't appear that there is much current documentation for using Dagger2 with AndroidX.

I do feel it is important to note I enabled AndroidX and Jetifier through gradle.properties:

android.useAndroidX=true
android.enableJetifier=true

However, nothing had changed after a clean and rebuild of the project.

What is the proper way to provide an Injection to an AndroidX fragment using Dagger2?

Edit: For the record, this is on Dagger 2 version 2.19. If I switch to using 2.16, everything works fine.

like image 579
josephoneill Avatar asked Nov 21 '18 02:11

josephoneill


People also ask

How do you inject an activity dagger?

To inject an object in the activity, you'd use the appComponent defined in your Application class and call the inject() method, passing in an instance of the activity that requests injection. When using activities, inject Dagger in the activity's onCreate() method before calling super.

What is dagger2 and why do you use it?

Dagger 2 is dependency injection framework. It is based on the Java Specification Request (JSR) 330. It uses code generation and is based on annotations. The generated code is very relatively easy to read and debug.


1 Answers

This is due to a mismatch in the Jetifier sources, as you can see from the below code:

# Androidx compatible dagger
{
    "from": { "groupId": "com.google.dagger", "artifactId": "dagger-android-processor", "version": "2.16" },
    "to": { "groupId": "com.google.dagger", "artifactId": "dagger-android-processor", "version": "2.16" }
}

From the release note of dagger-2.19:

In the next release (2.20), we will remove the old format. This will allow us to support AndroidX packages better.

So for now you either have to stick with version 2.16 or wait for the 2.20 release.

like image 131
Benjamin Avatar answered Oct 12 '22 04:10

Benjamin