[Solved] My app is crashing when I switch to dark mode


You’re casting the nullable Activity to a non-null Context in a listener that might be called when the Fragment it no longer attached to an Activity, which means the Activity would be null at that point.

You should generally avoid casting with as. In this case, it masks what the problem was. At least if you used !! to assert the Activity is not null, the stack trace would give you a more detailed explanation of what you did wrong.

Typically, you should use requireActivity() or requireContext() when you need to pass a non-null Context or Activity to something. They will give you the best error message when you use them where you shouldn’t. You should be aware of the Fragment lifecycle when you do this and know that it is not safe to get the non-null Activity during stages of the Fragment lifecycle where it might be detached.

(Incidentally, the LinearLayoutManager needs a non-null Activity as well, but it’s not annotated to require it, so the compiler let you get away with passing it a nullable activity. Its simpler to set it in the XML anyway.)

Since this is in an asynchronous response, you cannot predict whether the listener will be called while the Fragment is attached or not, so it is not safe to assume a non-null Activity. You should exit the function early if the Activity is null, since at this point there is no more UI to show the data anyway. Something like this:

Response.Listener {
    val attachedContext = activity ?: return@Listener

    // ...
    recl_view.adapter = MainAdapter(attachedContext, list)
    //...
}

It would be better to set up your request in a ViewModel so your current request isn’t wasted and rerun redundantly every time the screen rotates or dark mode is toggled. You are also temporarily leaking copies of your Fragment every time this happens because you don’t cancel the request when detached.

solved My app is crashing when I switch to dark mode