lateinit property NotaViewModel has not been initialized Error

So im trying to do an update in my sqlite data but its giving me error in the viewmodel. Its odd because in my Mainactivity i use one deletebyid and its working just fine, and error occurs when i click in the button, even if i put the notaViewModel.updateNotaByID(id, titulo.toString(), descricao.toString()) like notaViewModel.updateNotaByID(2, "static", "justtosee").

class EditarNota : AppCompatActivity() {

    private lateinit var tituloText: TextView
    private lateinit var descText: TextView
    **private lateinit var notaViewModel: NotaViewModel**
    override fun onCreate(savedInstanceState: Bundle?) {

        tituloText = findViewById(
        descText = findViewById(
        val id=intent.getIntExtra("id",0)
        val tit=intent.getStringExtra("tit")
        val desc=intent.getStringExtra("desc")

        tituloText.text = tit
        descText.text = desc
        val button = findViewById<Button>(
        button.setOnClickListener {
            var titulo = tituloText.text
            var descricao = descText.text
            if (id != null) {

                notaViewModel.updateNotaByID(id, titulo.toString(), descricao.toString())



E/AndroidRuntime: FATAL EXCEPTION: main
    Process: ipvc.estg.cmtrabalho, PID: 23245
    kotlin.UninitializedPropertyAccessException: lateinit property notaViewModel has not been initialized
        at ipvc.estg.cmtrabalho.EditarNota.access$getNotaViewModel$p(EditarNota.kt:11)
        at ipvc.estg.cmtrabalho.EditarNota$onCreate$1.onClick(EditarNota.kt:36)
        at android.view.View.performClick(
        at android.view.View$
        at android.os.Handler.handleCallback(
        at android.os.Handler.dispatchMessage(
        at android.os.Looper.loop(
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(

Answers 1

  • You dont need to use lateinit var for viewModel, you can use the 'by viewModels()' Kotlin property delegate

    val model: MyViewModel by viewModels()

Related Articles