Android ViewModel has no zero argument constructor
Solution 1:
In my case as I'm using HILT, it was lacking one annotation above the Fragment that has a ViewModel: @AndroidEntryPoint
@AndroidEntryPoint
class BestFragment : Fragment() {
....
Of course in your ViewModel class you also need to Annotate with what HILT needs: @ViewModelInject
class BestFragmentViewModel @ViewModelInject constructor(var userManager: UserManager) : ViewModel() {
....
}
Solution 2:
While initializing subclasses of ViewModel
using ViewModelProviders
, by default it expects your UserModel
class to have a zero argument constructor.
In your case your constructor has the argument MutableLiveData<User> user
.
One way to fix this is to have a default no arg constructor for your UserModel
.
Otherwise, if you want to have a non-zero argument constructor for your ViewModel class, you may have to create a custom ViewModelFactory
class to initialise your ViewModel instance, which implements the ViewModelProvider.Factory
interface.
I have not tried this yet, but here's a link to an excellent Google sample for this: github.com/googlesamples/android-architecture-components. Specifically, check out this class GithubViewModelFactory.java for Java code and this class GithubViewModelFactory.kt for the corresponding Kotlin code.