The requireActivity() and requireContext() example
Introduced in Support Library 27.1.0
This article is part of Today I Learned series and was originally posted at my TIL Github Repository and my website at wajahatkarim.com
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.
EDIT: Thanks to Ahmed Ashraf Gamal 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
Wajahat Karim is a graduate from NUST, Islamabad, an experienced mobile developer, an active open source contributor, and co-author of two books Learning Android Intents and Mastering Android Game Development with Unity. In his spare time, he likes to spend time with his family, do experiments on coding, loves to write about lots of things (mostly on blog and medium) and is passionate contributor to open source. In June 2018, one of his library became #1 on Github Trending. His libraries have about 2000 stars on Github and are being used in various apps by the developers all around the globe. Follow him on Twitter and Medium to get more updates about his work in Writing, Android and Open Source.
Also, if you have any questions you’d like him to answer, contact him through his website at wajahatkarim.com with DEAR WAJAHAT in the subject line.