[英]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.所以我试图在我的 sqlite 数据中进行更新,但它在视图模型中给了我错误。 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").这很奇怪,因为在我的 Mainactivity 中我使用了一个 deletebyid 并且它工作得很好,当我点击按钮时会发生错误,即使我把 notaViewModel.updateNotaByID(id, titulo.toString(), descicao.toString()) 像notaViewModel.updateNotaByID(2, "静态", "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您不需要为 viewModel 使用 lateinit var,您可以使用 'by viewModels()' Kotlin 属性委托
val model: MyViewModel by viewModels()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.