-2

I'm trying out a new architecture with multi-module and DI though Hilt, I have the following modules:

  • app: Contains MainActivity (which does nothing except holding fragment)
  • featureHome: Contains HomeFragment and HomeViewModel

When I start the app I'm getting java.lang.RuntimeException: Cannot create an instance of class HomeViewModel

App module

@AndroidEntryPoint
class MainActivity: AppCompatActivity()

FeatureHome

class HomeFragment: Fragment() {
    private val viewModel: HomeViewModel by viewModels()
    ...
}
@HiltViewModel
class HomeViewModel @Inject constructor(): ViewModel {
    ....
}

I'm not sure what to do to resolve this. Should my HomeFragment also have @AndroidEntryPoint ?

Biscuit
  • 4,840
  • 4
  • 26
  • 54
  • 1
    [An activity or a fragment that is annotated with @AndroidEntryPoint can get the ViewModel instance as normal using ViewModelProvider or the by viewModels() KTX extensions:](https://developer.android.com/training/dependency-injection/hilt-jetpack#viewmodels) – bylazy Apr 30 '23 at 06:45
  • Yes it works when the `HomeFragment` and `HomeViewModel` are in the same module as the `MainActivity` but when I move them to my `featureHome` module this doesn't work anymore – Biscuit Apr 30 '23 at 06:50
  • HomeFragment must also have @AndroidEntryPoint as the other comment suggests. And make sure hilt is in both modules. – jeprubio Apr 30 '23 at 08:07
  • But why ? When both Fragment and Activity are in the same package you don't need to have @AndroidEntryPoint on the Fragment – Biscuit Apr 30 '23 at 08:43
  • You are injecting the ViewModel in your fragment with `by viewModels()`. This requires the annotation to work. – Atick Faisal Apr 30 '23 at 10:03
  • 1
    Does this answer your question? [Cannot create an instance of class ViewModel](https://stackoverflow.com/questions/44998051/cannot-create-an-instance-of-class-viewmodel) – Victor Sklyarov Apr 30 '23 at 10:21
  • @AtickFaisal that's what I'm saying when HomeFragment is in the same module as MainActivity it is not needed, why the difference? – Biscuit Apr 30 '23 at 17:38

1 Answers1

0

Your Fragment has to be marked with the annotation @AndroidEntryPoint in order to tell Hilt to inject instances in your Fragment. (documentation)

Mikhail Guliaev
  • 1,168
  • 1
  • 6
  • 14