$ BadTokenException: невозможно добавить окно - нулевой токен не для приложения - Kotlin - PullRequest
0 голосов
/ 02 августа 2020

Я пытаюсь отобразить 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.
        }
    }

После показа всплывающего сообщения , приложение вылетает.

Сообщение об ошибке вставлено ниже:

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)

Я искал и пробовал различные решения. Пока ничего не помогло. Пожалуйста, помогите.

1 Ответ

1 голос
/ 02 августа 2020

Это вызывает ошибку, потому что не может найти текущее представление context, чтобы показать AlertDialog

Итак, вам нужно заменить val context = applicationContext на

val context = view.context
...