Difference between getActivity and requireActivity

Faisal ur Rehman
1 min readJun 13, 2022

--

I was using requireActivity for around 1 year. One day my friend ask me what is difference between getActivity(activity!! in case of kotlin) and requireActivity?

for just a moment I was thinking… then I was checking Android(Bible) Documentation.

after this as I understand They both invoke getActivity(). The only difference is requireActivity throw an IllegalStateException if the Activity is null. but getActivity return null when that Fragment is not attached to the Activity. requireActivity() returned exception and its message. Certainly, requireActivity() throws a more explicit exception.

Use cases:

In short, if you want to get the host activity inside fragment’s lifecycle methods, it’s ok to use requireActivity() without checking null. If you want to use the activity outside the lifecycle, for example, IO callback, it's better to check null + check destroyed. If you are 200% sure that in your fragment’s lifecycle, activity is not null, use requireActivity() as it needs no !! notation inside code, otherwise put it inside the try-catch block to avoid Exception.

Note: This was the first article I hope you like it.

Feel free to reach out on Twitter if you have any questions also visit my Linkedin profile.

--

--