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?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_new_note)
tituloText = findViewById(R.id.titulo)
descText = findViewById(R.id.desc)
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>(R.id.button_save)
button.setOnClickListener {
var titulo = tituloText.text
var descricao = descText.text
if (id != null) {
notaViewModel.updateNotaByID(id, titulo.toString(), descricao.toString())
}
}
}
}
Error:
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(View.java:4780)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
You dont need to use lateinit var for viewModel, you can use the 'by viewModels()' Kotlin property delegate
val model: MyViewModel by viewModels()