Cannot create an instance of class - ViewModel

前端 未结 2 1088
花落未央
花落未央 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 create(Class 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

提交回复
热议问题