The requireActivity() and requireContext() example

When we use Fragment in our app, we often time need access to Context or Activity. We do it by calling methods such as getContext() and getActivity() methods. But, in kotlin, these methods return nullables and we end up using code like this.

    fun myTempMethod()
    {
        context?.let {
            // Do something here regarding context
        }
        
        // Or we do it like this
        var myNonNullActivity = activity!!
    }

For example, we need Activity in asking permissions. So, with using above code approach, this will be:

    fun askCameraPermission()
    {
        PermissionUtils.requireCameraPermission(activity!!, REQUEST_CODE_CAMERA)
    }

Now, this code is very bad. When Fragment is not attached to any Activity, this code will crash and throw NullPointerException. Some developers avoid this by using as operator.

    fun askCameraPermission()
    {
        PermissionUtils.requireCameraPermission(activity as Activity, REQUEST_CODE_CAMERA)
    }

But, this is also almost same as bad as the previous example. Luckily, in Support Library 27.1.0 and later, Google has introduced new methods requireContext() and requireActivity() methods. So, we can do above example like this now:

    fun askCameraPermission()
    {
        PermissionUtils.requireCameraPermission(requireActivity(), REQUEST_CODE_CAMERA)
    }

Now, this method will make sure that Fragment is attached and returns a valid non-null Activity which we can use without any trouble.


If you liked this article, you can read my new articles below:


Wajahat Karim is Pakistan’s first Google Developer Expert in Android. As an experience Android developer, he deeply cares about it and keeps writing and speaking about it. He has written two worldwide 300+ pages books on Android development with more than 100 articles around the internet either on his website or his Medium publications. He is also a passionate contributor in open source and has created many Android libraries used by thousands of developers in their apps worldwide. As active public speaker, he spends lots of time giving talks in conferences and motivating people on Android development. You can find Wajahat most active on Twitter @WajahatKarim where he regularly shares all the good stuff about Android and community building.

Author's picture

Wajahat Karim

🔥 Google Dev Expert (GDE) in Android .
📱 Android Dev. 💻 Open Source Contributor . 📝 Technical Writer . 🎤 Public Speaker

Senior Android Developer

Karachi, Pakistan