Search code examples
androidandroid-activitykotlinadapter

Kotlin - "android.app.Application cannot be cast to android.app.Activity" on an Adapter


I'm trying to call an intent when select an item of a bottomNavigationView:

 R.id.nova_foto_barra_cartao -> {
      val intent = CameraView.buildIntent(context.applicationContext, Constants.ULCERS)
      (context as Activity).startActivityForResult(intent, 0)
 }

The code is written inside of an Adapter:

class CartaoTipologiaAdapter(private val cartoesTipologia: List<CartaoTipologia>, private val context: Context) : Adapter<CartaoTipologiaAdapter.ViewHolder>()

Solution

  • You're most likely passing an application context into the adapter, which you then cast to an Activity. So having a crash here is the expected behavior.

    It's safer to provide a custom callback from your adapter to the place where it is used. This lets you create the adapter without hard wiring its behavior to the activity. Then your callback implementation can take care of the action to perform.