Skip to content

Latest commit

History

History
49 lines (37 loc) 路 1.92 KB

req-act.md

File metadata and controls

49 lines (37 loc) 路 1.92 KB

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)
    }

Update

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

EDIT: Thanks to @humblerookie for pointing out that if the Fragment is not attached to the Activity , then the requireActivity() or requireContext() methods will throw IllegalStateException .

Credits: https://twitter.com/renaud_mathieu/status/1019222211004129282