Cannot create an instance of class ViewModel

后端 未结 23 2430
[愿得一人]
[愿得一人] 2020-12-05 12:37

I am trying to write a sample app using Android architecture components and but even after trying for days I could not get it to work. It gives me the above exception.

相关标签:
23条回答
  • 2020-12-05 13:14

    There are few reason to throw the exception . I have mention some of them..

    1. Make sure your view Model class is public
    2. Make sure your view model class constructor is public

    3. Make sure you have added the dependency in your gridle file for lifecycle also if you use room and other libries you have added ..

    4. if you create object any other dependent class in your view model class constructor . Other class can throw error to create the instance of viewModel
    0 讨论(0)
  • 2020-12-05 13:14

    Extend AndroidViewModel from your ViewModel class.

    public class YourViewModel extends AndroidViewModel {
    
        public YourViewModel(Application application) {
            super(application);
    
            //Todo: ...
        }
    
    }
    
    0 讨论(0)
  • 2020-12-05 13:14

    In my case, it was gradle a dependencies problem.

    If you are using Livedata,,

    build.gradle(Module.app)

    not

    implementation 'android.arch.lifecycle:extensions:1.1.1'
    kapt 'android.arch.lifecycle:common-java8:1.1.1'
    

    use these

    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    kapt 'androidx.lifecycle:lifecycle-common-java8:2.2.0'
    
    0 讨论(0)
  • 2020-12-05 13:16

    My problem was that the IDE had added a "abstract" modifier to my ViewModel class.

    0 讨论(0)
  • 2020-12-05 13:16

    I'm using this example android-arcuitecture-component BasicSample to make a new project, facing a similar error log, found I did'n change de applicatio name

    AndroidManifest.xml

    and that was my error, to fix put the aplicacion name to de BasicApp, this class is implement in the example.

    ...
    <application
        android:name=".BasicApp"
        android:allowBackup="false"
    
    0 讨论(0)
  • 2020-12-05 13:17

    If you used viewmodel inside your activity check that your activity extends "DaggerAppCompatActivity" or not

    For instance

    public class UserComments extends AppCompatActivity 
    

    change this to

    public class UserComments extends DaggerAppCompatActivity
    
    0 讨论(0)
提交回复
热议问题