Solution 1 :
The problem is that you’re depending on a specific implementation of Activity and that dependency (i.e. MainActivity
) is not satisfied in the code.
You’ll have to provide that as a binding in the same module:
@InstallIn(ActivityComponent::class)
@Module
object MainActivityModule {
@Provides
fun bindActivity(activity: Activity): MainActivity {
return activity as MainActivity
}
}
Problem :
I can’t compile the code using a Model View Presenter(MVP) Hilt approach.
I get this error:
/MotionPoC/app/build/generated/source/kapt/debug/com/aria/motionpoc/di/MotionApp_HiltComponents.java:145: error: [Dagger/MissingBinding] com.aria.motionpoc.coupon.MainActivity cannot be provided without an @Inject constructor or an @Provides-annotated method. This type supports members injection but cannot be implicitly provided.
The code itself:
MainActivity.kt
@AndroidEntryPoint
class MainActivity : AppCompatActivity(), MainContract.View {
@Inject
lateinit var presenter: MainContract.Presenter
MainPresenter.kt
class MainPresenter @Inject constructor(
private val view: MainContract.View
): MainContract.Presenter {
override fun onViewCreated() {
view.showList()
}
}
MainModule.kt
@InstallIn(ActivityComponent::class)
@Module
abstract class MainModule {
@Binds
abstract fun bindActivity(view: MainActivity): MainContract.View
@Binds
abstract fun bindPresenter(impl: MainPresenter): MainContract.Presenter
}
MotionApp.kt
@HiltAndroidApp
open class MotionApp : Application()
Solved! Thank you for the help Manuel Vivo!
https://github.com/riodext/AndroidDaggerHiltMVP
Comments
Comment posted by Javier Antón
You are missing @AndroidEntryPoint on your MainActivity and you have a Circle dependency which won’t compile. The activity needs a presenter and the presenter needs the activity to initialise
Comment posted by Arià
I already had the @AndroidEntryPoint (I forgot to put it here). And about the Cicle dependency, how would you implement the MVP? Thanks for answering!
Comment posted by Arià
I mean, how can I call methods from the View in my Presenter? Keeping both Activity and Presenter decoupled from each other.
Comment posted by Javier Antón
I would set the View in the presenter on the onCreate, and in onDestroy I would set it to null. Something like override onCreate(blabla) { super.onCreate(blala) presenter.setView(this) }
Comment posted by github.com/riodext/AndroidDaggerHiltMVP
I wanted to do the injection via constructor, and not manually. Solved in:
Comment posted by Arià
Thanks for answering! I tried this but I got this error in the bindActivity: /di/MainModule.java:21: error: @Binds methods’ parameter type must be assignable to the return type
Comment posted by manuelvicnt
Is that because your Activity is of other type? Try AppCompatActivity
Comment posted by github.com/riodext/AndroidDaggerHiltMVP
I uploaded the project in:
Comment posted by Arià
Solved! If anyone want to see the solution is in the link above
Comment posted by funct7
Worked well! Thank you.