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:


profile card
Wajahat Karim
🌍 Making the world a better place, one app at a time.
🔥 Google Developer Expert (GDE) in Android . 📱 Professional Android Developer with ~10 years experience. 💻 Creator of various Open Source libraries on Android . 📝 Author of two technical books and 100+ articles on Android. 🎤 A passionate Public Speaker giving talks all over the world.
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