Home > database >  Kotlin app crash when list refreshed on click
Kotlin app crash when list refreshed on click

Time:03-22

I've made an Android app that use a custom listview with an adapter, a refresh button and an onlick event for each row. My problem is that the first time that the list load all works well, but when i hit refresh then i click on a random row the app crashes with the following error:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?

In the onlick event i have a custom dialog with 4 buttons, the error is in the last row (builder.create().show()).

rowView.setOnClickListener {
    val builder = AlertDialog.Builder(context)
    builder.setTitle(context.getString(R.string.alert_commands_desc)   " "   recipe.valve)
    builder.setItems(
        arrayOf<CharSequence>(context.getString(R.string.open_valve_button),
            context.getString(R.string.close_valve_button),
            context.getString(R.string.deny_command_button),
            context.getString(R.string.close))
    ) { dialog, which ->
        when (which) {
            0 -> sendValveCommand("AV", recipe.id, context)
            1 -> sendValveCommand("CV", recipe.id, context)
            2 -> sendValveCommand("AC", recipe.id, context)
            3 -> dialog.dismiss()
        }
    }
    builder.create().show()
}

This is the adapter part:

if (json.has("Apparati_Controllo")) {
    val controlElementList = json.getJSONArray("Apparati_Controllo")
    val recipeList = ControlElement.populateRecipe(controlElementList)
    val adapter = ControlElementAdapter(thisContext, recipeList)
    listView.adapter = adapter
}

I tried by clearing adapter, list, change context, nothing works... Thanks a lot, tell me if you need more code.

CodePudding user response:

I never prefer using this or getApllicationContext() for any view that needs to be shown. Instead use this:

this@MyActivityName //in kotlin
MyActivityName.this //in java

Also add this in your AndroidManifest.xml

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
  • Related