Cannot create an instance of class - ViewModel

前端 未结 2 1089
花落未央
花落未央 2021-01-12 15:40

I\'m following an example of google, the example is in java but when I rewrite it in kotlin I can not instantiate the class. I am learning viewmodel. I have a lot o

相关标签:
2条回答
  • 2021-01-12 16:28

    I had the same issue, in JAVA though. My issue was solved with using the ViewModelFactory as follows:

    public class MyViewModelFactory implements ViewModelProvider.Factory {
        private Application mApplication;
    
    
    
        public MyViewModelFactory(Application application) {
            mApplication = application;
    
        }
        @Override
        public <T extends ViewModel> T create(Class<T> modelClass) {
            return (T) new BookViewModel(mApplication);
        }
    

    And where you call the ViewModel, change it to:

    mBookViewModel = new ViewModelProvider(this, new MyViewModelFactory
                    (this.getApplication())).get(BookViewModel.class);
    

    You can check this link for this issue from the tutorial's Github issues page: https://github.com/googlecodelabs/android-room-with-a-view/issues

    0 讨论(0)
  • 2021-01-12 16:31

    @zunjae

    Errors

    1 - Syntax code koltin.

    2 - Project configuration.

    class MainActivity: AppCompatActivity() {
    mWordViewModel = ViewModelProviders.of(this@MainActivity).get(WordViewModel(application)::class.java)
    

    ...

    class WordViewModel constructor (application: Application):  AndroidViewModel(application){
    

    ...

    class WordRepository constructor(application: Application) {
    

    ...

    add app build.gradle

    apply plugin: 'kotlin-kapt'
    
    kapt "android.arch.lifecycle:extensions:$rootProject.archLifecycleVersion"
    kapt "android.arch.persistence.room:compiler:$rootProject.roomVersion"
    
    0 讨论(0)
提交回复
热议问题