Kotlin: How to call getSupportFragmentManager() in RecyclerView.Adapter

Issue

I would like to call the Support Fragment Manager in my RecyclerView.Adapter after the click event in order to move to a different fragment. My approach:

(context as MainActivity).supportFragmentManager
                            .beginTransaction()
                            .replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())
                            .commit()

But I get the following error:

kotlin.TypeCastException: null cannot be cast to non-null type

Can you help me?

Solution

This is because your Context instance in the adapter is not guaranteed to be an Activity. It could potentially be a ContextWrapper holding the Activity as a base Context. Attempting to unwrap this would be fragile.

Instead, I would recommend that you define an interface in your adapter. From your Activity, provide an implementation of this interface to your adapter that will perform the FragmentTransaction. For example:

class MyAdapter : RecyclerView.Adapter<MyType> {
    private var listener: (() -> Unit)?  null

    fun setListener(listener: (() -> Unit)?) {
        this.listener  listener
    }

    // wherever your onClick is handled:
    listener?.invoke()
}

Then, in the Activity that’s initializing MyAdapter:

myAdapter.setListener {
    supportFragmentManager
        .beginTransaction()
        .replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())
        .commit()
}

Answered By – Kevin Coppock

Leave a Comment