首页 > 解决方案 > $BadTokenException:无法添加窗口——令牌 null 不适用于应用程序 - Kotlin

问题描述

我正在尝试从协程显示 AlertDialog。我的 AlertDialog 函数如下所示:

fun confirmDialogueBox(context : Context) {

// Late initialize an alert dialog object
lateinit var dialog: AlertDialog
// Initialize a new instance of alert dialog builder object
val builder = AlertDialog.Builder(ContextThemeWrapper(context, R.style.AlertBoxTheme))

// Set a title for alert dialog
builder.setTitle("Would you like to Download this Novel")

// On click listener for dialog buttons
val dialogClickListener = DialogInterface.OnClickListener { _, which ->
    when (which) {
        DialogInterface.BUTTON_POSITIVE -> Toast.makeText(context, "yes", Toast.LENGTH_SHORT)
            .show()
        DialogInterface.BUTTON_NEGATIVE -> Toast.makeText(context, "no", Toast.LENGTH_SHORT)
            .show()
        DialogInterface.BUTTON_NEUTRAL -> Toast.makeText(context, "cancel", Toast.LENGTH_SHORT)
            .show()
    }
}

// Set the alert dialog positive/yes button
builder.setPositiveButton("YES", dialogClickListener)

// Set the alert dialog negative/no button
builder.setNegativeButton("NO", dialogClickListener)

// Set the alert dialog neutral/cancel button
builder.setNeutralButton("CANCEL", dialogClickListener)
// Initialize the AlertDialog using builder object

// Finally, display the alert dialog
dialog = builder.create()
dialog.show()    //line 33 as in the error report.

}

如果单击 FloatingActionButton,我将调用此函数。

findViewById<FloatingActionButton>(R.id.fab).setOnClickListener { view ->
       
        val currentChapUrl = "https://novell.com/chapter-2.html"  
        val context = applicationContext
        GlobalScope.launch(Dispatchers.IO) {
            val resFromChapCountFunct = getTotalChapCount(context,currentChapUrl)  //suspend functoin
           
            if(resFromChapCountFunct > 0) {
                withContext(Dispatchers.Main)   {
                    Toast.makeText(context, "just a toast message", Toast.LENGTH_SHORT).show()   //upto this its working.
                    confirmDialogueBox(context)
                }
            }
            downloadChapters(context,currentChapUrl)  //download chapters from the current chapter number until the last chapter available.
        }
    }

显示 toast 消息后,应用程序崩溃。

错误消息粘贴在下面:

2020-08-02 10:28:25.943 4815-4923/com.example.daoreader E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: com.example.daoreader, PID: 4815
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
    at android.view.ViewRootImpl.setView(ViewRootImpl.java:683)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
    at android.app.Dialog.show(Dialog.java:322)
    at com.example.daoreader.ConfirmDialogueBoxKt.confirmDialogueBox(confirmDialogueBox.kt:44)
    at com.example.daoreader.WebviewActivity$onCreate$1$1$1.invokeSuspend(WebviewActivity.kt:33)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

我已经搜索并尝试了各种解决方案。到目前为止没有工作。请帮忙。

标签: androidkotlinandroid-alertdialogkotlin-coroutines

解决方案


它会导致错误,因为它找不到当前视图context来显示AlertDialog

所以你需要做的是替换val context = applicationContext

val context = view.context

推荐阅读