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
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
@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"