I've been trying to resolve my issue but I can't find anything...
MyApp.kt :
#HiltAndroidApp
class MyApp: Application()
MainActivity.kt
#AndroidEntryPoint
class MainActivity: AppCompatActivity()
MyFragment.kt
class MyFragment: Fragment() {
private val myViewModel: MyViewModel by viewModels()
}
MyViewModel.kt
class MyViewModel #ViewModelInject constructor(
application: Application,
myRepository: MyRepository, {*}
#Assisted private val state: SavedStateHandle,
): AndroidViewModel(application)
MyRepository.kt
interface MyRepository {
fun test()
}
class MyRepositoryImpl #Inject constructor(): MyRepository {
override fun test() { print("") }
}
MyModule.kt
#Module
#InstallIn(SingletonComponent::class)
abstract class MyModule {
#Binds
abstract fun bindsMyRepository(impl: MyRepositoryImpl): MyRepository
}
If I comment the line with "{*}", it works fine, but since I try to add my custom repository, I got this error :
java.lang.RuntimeException: Cannot create an instance of class MyViewModel
Caused by: java.lang.NoSuchMethodException: [class android.app.Application]
Do you have any idea of what I am missing?
Thanks you!
Complementary informations:
I forgot to mention that this is a multi module app.
In the first module, there is the basic app : MainActivity, a manifest (1)
In the second module, there is the core app : MyApp, a manifest (2)
In the third module, there is the module : MyFragment, MyViewModel, MyRepository and MyModule, a manifest (3)
Manifests are like this:
(1)
<manifest...>
<application...
android:name=".secondModule.MyApp">
</manifest>
(2)
<manifest...>
<application>
<provider...></provider>
</application>
</manifest>
(3)
<manifest.../>
First Annotate your fragment
#AndroidEntryPoint
class MyFragment: Fragment() {
private val myViewModel: MyViewModel by viewModels()
}
Secondly you have to extend ViewModel instead of AndroidViewModel
class MyViewModel #ViewModelInject constructor(
#Application context : Context ,
myRepository: MyRepository, {*}
#Assisted private val state: SavedStateHandle,
): ViewModel()
Subsitute SingletonComponent With ApplicationComponent
#Module
#InstallIn(ApplicationComponent::class)
abstract class MyModule {
#Binds
abstract fun bindsMyRepository(impl: MyRepositoryImpl): MyRepository
}
PS : Don't forget to add your application class( MyApp ) to your manifest file
You must use #AndroidEntryPoint for your fragments
#AndroidEntryPoint
class MyFragment: Fragment() {
private val myViewModel: MyViewModel by viewModels()
}
Also ApplicationComponent was removed in Dagger 2.30, but it is used in androidx.hilt:hilt (#ViewModelInject).
They added ApplicationComponent back in 2.31.1 because of the library mentioned above.
Update your Dagger version to 2.31.1 (use SingletonComponent instead of ApplicationComponent) or use new feature Hilt View Models
#HiltViewModel
class MyViewModel #Inject constructor(
private val application: Application,
myRepository: MyRepository,
private val state: SavedStateHandle,
): ViewModel()
Related
Before, I use Code A to pass Context to ViewModel.
Now I hope to use Hilt as dependency injection to pass Context,
I have read the article , and Code B is from the article.
1: Is the Code B correct way to pass Context into ViewModel?
2: In my mind, in order to use Hilt in Android Studio project, I have added such as the Code C in project, do I need to use fun provideApplicationContext() = MyApplication() in Code B?
Code A
class HomeViewModel(private val mApplication: Application, val mRepository: DBRepository) : AndroidViewModel(mApplication) {
...
}
Code B
class MainViewModel #ViewModelInject constructor(
#ApplicationContext private val context: Context,
private val repository: Repository,
#Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
...
}
#Singleton
#Provides
fun provideApplicationContext() = MyApplication()
Code C
#HiltAndroidApp
class MyApplication : Application() {
}
This is how I injected applicationContext in the viewmodel and it worked fine.
Base Application
#HiltAndroidApp
class BaseApplication: Application()
App Module
#Module
#InstallIn(SingletonComponent::class)
object AppModule {
#Singleton
#Provides
fun provideApplication(#ApplicationContext app: Context): BaseApplication{
return app as BaseApplication
}
View Model
#HiltViewModel
class PendingListViewModel
#Inject
constructor(private val application: BaseApplication)
Usage In the ViewModel
AppCompatResources.getDrawable(application.applicationContext, R.drawable.marker_circle)
Based on the Hilt tutorial, ViewModels needs to be inject the following way:
#HiltViewModel
class ExampleViewModel #Inject constructor(
private val savedStateHandle: SavedStateHandle,
private val repository: ExampleRepository
) : ViewModel() {
...
}
However, in my case, I want to use an interface:
interface ExampleViewModel()
#HiltViewModel
class ExampleViewModelImp #Inject constructor(
private val savedStateHandle: SavedStateHandle,
private val repository: ExampleRepository
) : ExampleViewModel, ViewModel() {
...
}
Then I want to inject it via the interface
#AndroidEntryPoint
class ExampleActivity : AppCompatActivity() {
private val exampleViewModel: ExampleViewModel by viewModels()
...
}
How to make this work?
viewModels requires child of ViewModel class
val viewModel: ExampleViewModel by viewModels<ExampleViewModelImp>()
Had a similar problem where I wanted to Inject the ViewModel via interface, primarily because to switch it with a fake implementation while testing. We are migrating from Dagger Android to Hilt, and we had UI tests that used fake view models. Adding my findings here so that it could help someone whose facing a similar problem.
Both by viewModels() and ViewModelProviders.of(...) expects a type that extends ViewModel(). So interface won't be possible, but we can still use an abstract class that extends ViewModel()
I don't think there is a way to use #HiltViewModel for this purpose, since there was no way to switch the implementation.
So instead, try to inject the ViewModelFactory in the Fragment. You can switch the factory during testing and thereby switch the ViewModel.
#AndroidEntryPoint
class ListFragment : Fragment() {
#ListFragmentQualifier
#Inject
lateinit var factory: AbstractSavedStateViewModelFactory
private val viewModel: ListViewModel by viewModels(
factoryProducer = { factory }
)
}
abstract class ListViewModel : ViewModel() {
abstract fun load()
abstract val title: LiveData<String>
}
class ListViewModelImpl(
private val savedStateHandle: SavedStateHandle
) : ListViewModel() {
override val title: MutableLiveData<String> = MutableLiveData()
override fun load() {
title.value = "Actual Implementation"
}
}
class ListViewModelFactory(
owner: SavedStateRegistryOwner,
args: Bundle? = null
) : AbstractSavedStateViewModelFactory(owner, args) {
override fun <T : ViewModel?> create(
key: String,
modelClass: Class<T>,
handle: SavedStateHandle
): T {
return ListViewModelImpl(handle) as T
}
}
#Module
#InstallIn(FragmentComponent::class)
object ListDI {
#ListFragmentQualifier
#Provides
fun provideFactory(fragment: Fragment): AbstractSavedStateViewModelFactory {
return ListViewModelFactory(fragment, fragment.arguments)
}
}
#Qualifier
annotation class ListFragmentQualifier
Here, ListViewModel is the abstract class and ListViewModelImpl is the actual implementation. You can switch the ListDI module while testing using TestInstallIn. For more information on this, and a working project refer to this article
Found a solution using HiltViewModel as a proxy to the actual class I wish to inject. It is simple and works like a charm ;)
Module
#Module
#InstallIn(ViewModelComponent::class)
object MyClassModule{
#Provides
fun provideMyClas(): MyClass = MyClassImp()
}
class MyClassImp : MyClass {
// your magic goes here
}
Fragment
#HiltViewModel
class Proxy #Inject constructor(val ref: MyClass) : ViewModel()
#AndroidEntryPoint
class MyFragment : Fragment() {
private val myClass by lazy {
val viewModel by viewModels<Proxy>()
viewModel.ref
}
}
Now you got myClass of the type MyClass interface bounded to viewModels<Proxy>() lifeCycle
It's so simple to inject an interface, you pass an interface but the injection injects an Impl.
#InstallIn(ViewModelComponent::class)
#Module
class DIModule {
#Provides
fun providesRepository(): YourRepository = YourRepositoryImpl()
}
i am try to inject a module to MyViewModel
here is my Module
#Module
#InstallIn(ViewModelComponent::class)
object EngineModule {
#Provides
fun getEngine(): String = "F35 Engine"
}
and this my viewModel
#HiltViewModel
class MyViewModel #Inject constructor(): ViewModel() {
#Inject lateinit var getEngine: String
fun getEngineNameFromViewModel(): String = getEngineName()
}
and it throws
kotlin.UninitializedPropertyAccessException: lateinit property getEngine
has not been initialized
however if i change ViewModelComponent::class to ActivityComponent::class and inject like this
#AndroidEntryPoint
class MainActivity : ComponentActivity() {
#Inject
lateinit var getEngine: String
it works perfectly
any idea how to inject viewModels?
Also you can just remove #Inject constructor since you are already providing the dependency using dagger module:
#HiltViewModel
class MyViewModel (private val engineName: String): ViewModel() {
fun getEngineNameFromViewModel(): String = engineName
}
So, Basically you can either provide the dependency using dagger module or constructor injection.
Since required dependency is going to be injected in the ViewModel's constructor, you just need to modify your code in the following way to make it work:
#HiltViewModel
class MyViewModel #Inject constructor(private val engineName: String): ViewModel() {
fun getEngineNameFromViewModel(): String = engineName
}
I have a ViewModelFactory implemented as follows:
class ViewModelFactory<VM> #Inject constructor(private val viewModel: Lazy<VM>)
: ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
#Suppress("UNCHECKED_CAST")
return viewModel.get() as T
}
}
This works fine with my current ViewModel:
class MainActivityViewModel #Inject constructor(private val dependency: Dependency) : ViewModel()
//... in the activity:
#Inject
lateinit var factory: ViewModelFactory<MainActivityViewModel>
private val viewModel: MainActivityViewModel by viewModels { factory }
However I have a different build flavour that I want to implement where the behaviour is different, so I have created an AbstractViewModel:
abstract class AbstractViewModel : ViewModel()
//...and so now
class MainActivityViewModel #Inject constructor(private val dependency: Dependency) : AbstractViewModel()
//... and in the activity
#Inject
lateinit var factory: ViewModelFactory<AbstractViewModel>
private val viewModel: AbstractViewModel by viewModels { factory }
I want to be able to provide the specific instance to the ViewModelFactory, but I am not sure how to achieve this.
Solved it. Answering for future reference and anyone who may be interested in doing something similar.
Step 1: Add a new module component
#Component(
modules = [
//...
ViewModelModule::class
]
)
interface ApplicationComponent { //...
This allows developers to create a FlavourApplicationComponent that can have an alternate to ViewModelModule, which I called MockViewModelModule
Step 2: Define the modules
//in the main flavour
#Module
class ViewModelModule {
#Provides
fun provideMainActivityViewModel(mainActivityViewModel: MainActivityViewModel): AbstractViewModel
= mainActivityViewModel
}
//in the mock flavour
#Module
class MockViewModelModule {
#Provides
fun provideMainActivityViewModel(mainActivityViewModel: MainActivityViewModel): AbstractViewModel
= MockMainActivityViewModel()
}
And this can actually be configured at run time, and therefore you can allow users to test all the different states of your app without them needing to GET into those states.
I have an Android project with Hilt dependency injection. I have defined MyApplication and MyModule as follows.
#HiltAndroidApp
class MyApplication : Application()
#Module
#InstallIn(ApplicationComponent::class)
abstract class MyModule {
#Binds
#Singleton
abstract fun bindMyRepository(
myRepositoryImpl: MyRepositoryImpl
): MyRepository
}
MyRepositoryImpl implements the MyRepository interface:
interface MyRepository {
fun doSomething(): String
}
class MyRepositoryImpl
#Inject
constructor(
) : MyRepository {
override fun doSomething() = ""
}
I can now inject this implementation of MyRepository into a ViewModel:
class MyActivityViewModel
#ViewModelInject
constructor(
private val myRepository: MyRepository,
) : ViewModel() { }
This works as expected. However, if I try to inject the repository into a service, I get an error java.lang.Class<MyService> has no zero argument constructor:
class MyService
#Inject
constructor(
private val myRepository: MyRepository,
): Service() { }
The same error occurs with an activity, too:
class MyActivity
#Inject
constructor(
private val myRepository: MyRepository,
) : AppCompatActivity(R.layout.my_layout) { }
What am I doing wrong with the injection?
From the documentation on how we Inject dependencies into Android classes, we can learn the following:
Hilt can provide dependencies to other Android classes that have the #AndroidEntryPoint annotation.
Hilt currently supports the following Android classes:
Application (by using #HiltAndroidApp)
ViewModel (by using #HiltViewModel)
Activity
Fragment
View
Service
BroadcastReceiver
So when you subclass any of these Android classes, you don't ask Hilt to inject dependencies through the constructors. Instead, you annotate it with #AndroidEntryPoint, and ask Hilt to inject its dependencies by annotating the property with #Inject:
#AndroidEntryPoint
class ExampleActivity : AppCompatActivity() {
#Inject
lateinit var mAdapter: SomeAdapter
...
}
So, in your case you should inject MyRepository in MyActivity and MyService like this:
#AndroidEntryPoint
class MyService: Service() {
#Inject
lateinit var myRepository: MyRepository
...
}
#AndroidEntryPoint
class MyActivity: AppCompatActivity(R.layout.my_layout) {
#Inject
lateinit var myRepository: MyRepository
...
}
And remember:
Fields injected by Hilt cannot be private
That's it for Android classes that is supported by Hilt.
If you wonder what about classes not supported by Hilt (ex: ContentProvider)?! I recommend learning how from this tutorial #EntryPoint annotation on codelab (also don't forget to check the documentation for how to Inject dependencies in classes not supported by Hilt).
Also If you overriding onCreate in your Service - don't forget to add super.onCreate() otherwise you will get runtime exception that the myRepository value cannot be initialised (I was struggling with this error for some time during refactoring my service so maybe it will be helpful for somebody)
#AndroidEntryPoint
class MyService : Service() {
#Inject
lateinit var myRepository: MyRepository
override fun onCreate() {
super.onCreate()
}
}
Your use of #Inject on the MyService class is as if MyService is to be injected at some other location.
If I understand correctly, you want something more akin to:
#AndroidEntryPoint
class MyService : Service() {
#Inject
lateinit var myRepository: MyRepository
}