androidandroid-activityandroid-jetpack-compose

Context cannot be cast to android.app.Activity error


I recently updated the gradle dependencies and right after that I started getting this error:

android.view.ContextThemeWrapper cannot be cast to android.app.Activity

The code where the error originates is the following:

val activity = LocalContext.current as Activity

I need the activity in this function shouldShowRequestPermissionRationale(activity, permission).

In other posts on this site I can see that it is usually the way to cast the context to an activity. What could have happened with the update of the dependency? Are there any alternative?

I tried changing the dependencies I thought could be responsible to a previous version but nothing worked


Solution

  • You can use recursive solution:

    fun Context.findActivity(): Activity? =
        when (this) {
            is Activity -> this
            is ContextWrapper -> baseContext.findActivity()
            else -> null
        }
    

    And wrap it around let before use:

    val context = LocalContext.current
    context.findActivity()?.let { activity ->
        // Code
    }