Caused by: kotlin.UninitializedPropertyAccessException: lateinit 属性 对话框尚未初始化

Caused by: kotlin.UninitializedPropertyAccessException: lateinit property dialog has not been initialized

我刚开始学习 Kotlin。我正在使用自定义 ProgressDialog。每次我从 MainActivity 返回时,应用程序都会崩溃并出现以下错误:

  Caused by: kotlin.UninitializedPropertyAccessException: lateinit property dialog has not been initialized
    at com.devApps.blog.CustomProgressDialog.getDialog(CustomProgressDialog.kt:17)

这是我的 CustomProgressDialog:

  private val progressDialognew = CustomProgressDialog()
  lateinit var dialog: CustomDialog

fun show(context: Context): Dialog {
    return show(context, null)
}

fun show(context: Context, title: CharSequence?): Dialog {
    val inflater = (context as Activity).layoutInflater
    val view = inflater.inflate(R.layout.progress_dialog_view, null)
    if (title != null) {
        view.cp_title.text = title
    }
    dialog = CustomDialog(context)
    dialog.setContentView(view)
    dialog.show()
    return dialog
}

这是我的 MainActivity 代码:

 private val progressDialognew = CustomProgressDialog()
 progressDialognew.show(this, "Optimizing Image...")
 {
    my tasks here
 }

  override fun onDestroy() {
    super.onDestroy()
    progressDialognew.dialog.dismiss()
}

更新:我按照建议做了,现在我在 return 对话框行的 show() 中遇到了同样的错误。如何解决?

 lateinit var dialog: CustomDialog


fun show(context: Context): Dialog {
    return show(context, null)
}

fun show(context: Context, title: CharSequence?): Dialog {
    if (::dialog.isInitialized) {
        val inflater = (context as Activity).layoutInflater
        val view = inflater.inflate(R.layout.progress_dialog_view, null)
        if (title != null) {
            view.cp_title.text = title
        }

        dialog = CustomDialog(context)
        dialog.setContentView(view)
        dialog.show()
       
    }
    return dialog
}

   
}

fun hideProgress() {

    if (::dialog.isInitialized) {
        if (dialog != null) {
            dialog.dismiss()
        }

    }

完成 StackTrace:

 kotlin.UninitializedPropertyAccessException: lateinit property dialog has not been initialized
    at com.devApps.blog.CustomProgressDialog.show(CustomProgressDialog.kt:50)
    at com.devApps.blog.PostActivity.upload(PostActivity.kt:328)
    at com.devApps.blog.PostActivity.post(PostActivity.kt:320)
    at com.devApps.blog.PostActivity.access$post(PostActivity.kt:54)
    at com.devApps.blog.PostActivity$onCreate.onClick(PostActivity.kt:198)

如果您在不显示对话框的情况下关闭 activity,则会发生此异常。因为 CustomProgressDialog 中的 dialog 属性 仅在 show() 方法中初始化。

并且 activity 的 onDestroy() 方法调用 dialog 属性 上的 dismiss() 可能未初始化。

你可以在关闭之前先检查它是否初始化,考虑在CustomProgressDialog中添加这个方法:

fun dismissDialog() {
    if (::dialog.isInitialized) {
        dialog.dismiss()
    }
}

并从 activity:

调用它
override fun onDestroy() {
    super.onDestroy()
    progressDialognew.dismissDialog()
}