i’am using retrofit library to get info from internet api , then i put the data in the repository then get it in viewmodel which it will be instatiate by viewmodelfactory ;
so i’am trying to inject HitViewModelFactory by using Dagger-Hilt in Fragment but it show me an error when to inject it in the fragment
lateinit property hitViewModelFactory has not been initialized
i make an application class and anotate it with @HiltAndroidApp and give the name of application in manifest. and make anotate to activity that host this fragment but the problem not solved
@AndroidEntryPoint
class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
.......
}
}
i provide all dependencies that i need in the module class :
@Module
@InstallIn(ApplicationComponent::class)
object AppModule {
@Singleton
@Provides
fun provideHitPhotoApi() = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(HitApi::class.java)
@Singleton
@Provides
fun provideHitRepository(hitApi: HitApi) = HitRepository(hitApi)
@Singleton
@Provides
fun provideHitViewModelFactory(hitRepository: HitRepository) : HitViewModelFactory = HitViewModelFactory(hitRepository)
}
and try to inject ViewModelFactory in this fragment
@AndroidEntryPoint
class TripsFragment : Fragment() {
@Inject
lateinit var hitViewModelFactory: HitViewModelFactory
lateinit var hitViewModel: HitViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
hitViewModel = ViewModelProvider(requireActivity(),hitViewModelFactory)[HitViewModel::class.java ]
}
dependency for hilt :
Dagger - Hilt
implementation "com.google.dagger:hilt-android:2.28-alpha"
kapt "com.google.dagger:hilt-android-compiler:2.28-alpha"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-
alpha03"
kapt "androidx.hilt:hilt-compiler:1.0.0"
2
Answers
the problem solved when i change the dependency of Hilt to :
and for these dependencies it should replace the InstallIn anotation for module class to SingletonComponent::class like
I also faced same issue earlier. Not sure why this fails but it seems code is correct.
So I have done with different approach.
I created view model like this below. And I inject HitApi directly in viewmodel constructor. Then just initialize like below. It takes care of creating viewmodel instance and hilt takes care of injection.No need of creating factory.
ViewModel:
Fragment:
Make sure you have these dependancies.