Cannot create an instance of class - ViewModel
Asked Answered
A

2

6

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 of doubt if I messed up the syntax of my kotlin code.

https://github.com/googlecodelabs/android-room-with-a-view

Error class MainActivity: AppCompatActivity() {

//    private lateinit var mWordViewModel: WordViewModel //not works
    private var mWordViewModel: WordViewModel? = null //not works
    private var wordListAdapter: WordListAdapter?= null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        try {
            mWordViewModel = ViewModelProviders.of(this@MainActivity).get(WordViewModel::class.java)
        }catch (e: Exception){
            e.printStackTrace()
        }

...

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

//    super(application)

    private var mRepository: WordRepository? = null
    private var mAllWords: LiveData<List<Word>>? = null

    init {
        mRepository = WordRepository(application)
        mAllWords = mRepository?.getAllWords()
    }

...

class WordRepository(application: Application) {

    private var mWordDao: WordDao? = null
    private var mAllWords: LiveData<List<Word>>? = null

    init {
        val db = WordRoomDatabase.getDatabase(application)
        mWordDao = db.wordDao()
        mAllWords = mWordDao!!.getAlphabetizeWords()
    }

...

@Database(entities = arrayOf(Word::class), version = 1)
abstract class WordRoomDatabase: RoomDatabase(){

    abstract fun wordDao(): WordDao

    companion object {
        @JvmStatic
        private var INSTANCE: WordRoomDatabase? = null

        fun getDatabase(context: Context): WordRoomDatabase {
            if (INSTANCE == null) {
                synchronized(WordRoomDatabase::class.java) {
                    if (INSTANCE == null) {
                        INSTANCE = Room.databaseBuilder(context.applicationContext, WordRoomDatabase::class.java, "word_database")
                                .fallbackToDestructiveMigration()
                                .addCallback(sRoomDatabaseCallback)
                                .build()
                    }
                }
            }
            return INSTANCE!!
        }
Atrophied answered 21/6, 2018 at 12:50 Comment(3)
Can you provide a full stack trace?Longplaying
Process: com.example.felippe.livedata, PID: 11852 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.felippe.livedata/com.example.felippe.livedata.MainActivity}: kotlin.KotlinNullPointerException @ElectroWeakAtrophied
That is just the beginning of stack trace. Copy the whole text.Longplaying
A
8

@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"
Atrophied answered 22/6, 2018 at 17:12 Comment(0)
L
4

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

Luau answered 29/6, 2020 at 9:12 Comment(1)
any idea how to solve , in case we are using a fragment instead of an activity?Tyrannize

© 2022 - 2024 — McMap. All rights reserved.