Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hilt ClassCastException: ViewComponentManager$FragmentContextWrapper cannot be cast to AppCompatActivity

I have this code where I show Dialog Fragment when clicking a viewHolder item in Adapter

 SpecialRequestNotFoundBottomSheetDialog {
            requestItem?.specialRequestEntity?.id?.let { id -> onCancelReasonsSelected(id, it) }
        }.show(itemView.context as AppCompatActivity).supportFragmentManager)

recently I'm migrating to Hilt and I got class cast exception, looks like Hilt wrapping the context and I can't get the parent Activity to get the required FragmentManager to show the Dialog

like image 899
Mohamed Ibrahim Avatar asked Aug 18 '20 00:08

Mohamed Ibrahim


2 Answers

I read source code find this solution FragmentComponentManager.findActivity(view.context) as Activity

like image 141
stronglee1346 Avatar answered Nov 05 '22 04:11

stronglee1346


I may found a workaround to this crash by checking the Context type and getting the BaseContext. Here's what I'm using now. I don't know if there's a better way to do it with Hilt.

private fun activityContext(): Context? {
    val context = itemView.context
    return if (context is ViewComponentManager.FragmentContextWrapper) {
        context.baseContext
    } else context
}
like image 31
Mohamed Ibrahim Avatar answered Nov 05 '22 03:11

Mohamed Ibrahim