ViewModel has no zero argument constructor hilt Java
Asked Answered
B

3

32

I am using hilt and I am trying to import my SessionManager into my AuthViewModel class.

When I am taking a look at Google's documentation on hilt with ViewModel. We can see they are able to inject ExampleRepository repository into the constructor of said ExampleViewModel

public class ExampleViewModel extends ViewModel {

  private final ExampleRepository repository;
  private final SavedStateHandle savedStateHandle;

  @ViewModelInject
  ExampleViewModel(
      ExampleRepository repository,
      @Assisted SavedStateHandle savedStateHandle)
    {
    this.repository = repository;
    this.savedStateHandle = savedStateHandle;
  }
  ...
}

and

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    exampleViewModel = new ViewModelProvider(this).get(ExampleViewModel.class);
  }

Whenever I try to do this with my project I keep on getting the error.

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.atchat.donation, PID: 11005
    java.lang.RuntimeException: Cannot create an instance of class com.atchat.donation.ui.auth.AuthViewModel
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:278)
        at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
        at androidx.hilt.lifecycle.HiltViewModelFactory.create(HiltViewModelFactory.java:74)
        at androidx.lifecycle.AbstractSavedStateViewModelFactory.create(AbstractSavedStateViewModelFactory.java:69)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.atchat.donation.ui.auth.LoginFragment.onViewCreated(LoginFragment.java:97)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:332)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1199)
        at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2236)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2009)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1965)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1861)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2641)
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2589)
        at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2723)
        at androidx.fragment.app.FragmentStateManager.activityCreated(FragmentStateManager.java:346)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1200)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1368)
        at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1446)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1509)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2637)
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2589)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1425)
        at android.app.Activity.performStart(Activity.java:7825)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3294)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.InstantiationException: java.lang.Class<com.atchat.donation.ui.auth.AuthViewModel> has no zero argument constructor
        at java.lang.Class.newInstance(Native Method)
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:278) 
        at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106) 
        at androidx.hilt.lifecycle.HiltViewModelFactory.create(HiltViewModelFactory.java:74) 
        at androidx.lifecycle.AbstractSavedStateViewModelFactory.create(AbstractSavedStateViewModelFactory.java:69) 
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185) 
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150) 
        at com.atchat.donation.ui.auth.LoginFragment.onViewCreated(LoginFragment.java:97) 
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:332) 
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1199) 
        at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2236) 
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2009) 
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1965) 
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1861) 
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2641) 
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2589) 
        at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2723) 
        at androidx.fragment.app.FragmentStateManager.activityCreated(FragmentStateManager.java:346) 
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1200) 
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1368) 
        at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1446) 
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1509) 
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2637) 
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2589) 
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247) 
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541) 
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210) 
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1425) 
        at android.app.Activity.performStart(Activity.java:7825) 
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3294) 
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221) 
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201) 
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7356) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
I/Process: Sending signal. PID: 11005 SIG: 9

AuthViewModel

public class AuthViewModel extends ViewModel {

    private static final String TAG = "AuthViewModel";
    private final SessionManager sessionManager;

    @ViewModelInject
    public AuthViewModel(SessionManager sessionManager, @Assisted SavedStateHandle savedStateHandle){
        this.sessionManager = sessionManager;
    }
...
}

AppModule

@Module()
@InstallIn(SingletonComponent.class)
public class AppModule {

    @Provides
    public static SessionManager provideSessionManager(@ApplicationContext Context context, AccountRestService accountRestService){
        return new SessionManager(accountRestService, context);
    }
...
}

LoginFragment

@AndroidEntryPoint
public class LoginFragment extends Fragment implements View.OnClickListener {

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewModel = new ViewModelProvider(this).get(AuthViewModel.class);
        subscribeObservers();
        attemptSilentLogin();
    }
...
}

build.gradle (Module)

apply plugin: 'dagger.hilt.android.plugin'

dependencies {
    //Hilt
    implementation 'com.google.dagger:hilt-android:2.30-alpha'
    implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha02'
    annotationProcessor 'com.google.dagger:hilt-android-compiler:2.30-alpha'
...
}

build.gradle (Project)

dependencies {
    classpath 'com.android.tools.build:gradle:4.1.1'
    classpath 'com.google.dagger:hilt-android-gradle-plugin:2.30-alpha'
}
Backchat answered 30/11, 2020 at 0:59 Comment(2)
Can you include the entire stack trace (rather than only the first line)?Bunker
@Bunker I have included the full stack traceBackchat
B
23

Your error message shows that the HiltViewModelFactory doesn't have a binding for your specific AuthViewModel. It doesn't because you haven't included the additional annotationProcessor that is needed specifically for Hilt and Jetpack integrations - it is that extra androidx.hilt:hilt-compiler annotation processor that is responsible for reading the @ViewModelInject and generating the correct Hilt bindings.

dependencies {
    // Hilt
    implementation 'com.google.dagger:hilt-android:2.30-alpha'
    annotationProcessor 'com.google.dagger:hilt-android-compiler:2.30-alpha'

    // Hilt Jetpack Integrations
    implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha02'
    annotationProcessor 'androidx.hilt:hilt-compiler:1.0.0-alpha02'
...
}
Bunker answered 30/11, 2020 at 1:54 Comment(2)
I'd missed this in the docs, but I'd also forgotten to add @AndroidEntryPoint to my Activity (which seems to give an identical error).Liveried
Also: Same error can appear if the @HiltViewModel annotation is missing for the ViewModel class itselfColobus
M
94

I too faced this error, What I missed was I forgot to add @AndroidEntryPoint in MyFragment.

So Make Sure to Add all necessary Annotations.

Microgram answered 21/5, 2021 at 14:1 Comment(0)
B
23

Your error message shows that the HiltViewModelFactory doesn't have a binding for your specific AuthViewModel. It doesn't because you haven't included the additional annotationProcessor that is needed specifically for Hilt and Jetpack integrations - it is that extra androidx.hilt:hilt-compiler annotation processor that is responsible for reading the @ViewModelInject and generating the correct Hilt bindings.

dependencies {
    // Hilt
    implementation 'com.google.dagger:hilt-android:2.30-alpha'
    annotationProcessor 'com.google.dagger:hilt-android-compiler:2.30-alpha'

    // Hilt Jetpack Integrations
    implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha02'
    annotationProcessor 'androidx.hilt:hilt-compiler:1.0.0-alpha02'
...
}
Bunker answered 30/11, 2020 at 1:54 Comment(2)
I'd missed this in the docs, but I'd also forgotten to add @AndroidEntryPoint to my Activity (which seems to give an identical error).Liveried
Also: Same error can appear if the @HiltViewModel annotation is missing for the ViewModel class itselfColobus
B
3

I'm using Hilt in Kotlin, I got the same Error: "Cannot instantiate viewmodel ... has no zero arguments constructor"
I already inserted all annotation: @HiltAndroidApp, @AndroidEntryPoint ...
But I missed one: @HiltViewModel, after inserting that on top of my viewmodel, all errors gone.

@HiltViewModel //I missed this annotation
class LoginViewModel @Inject constructor(
    private val loginUseCase: LoginUseCase
) : ViewModel() {

}
Bedabble answered 12/6, 2022 at 6:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.