According to the support library changelog and the Fragment class documentation (https://developer.android.com/reference/android/support/v4/app/Fragment.html), there are now new methods like requreActivity() and requireContext().
What is the purpose of these methods compared to getActivity() and getContext(), since they can still throw IllegalStateExceptions? Is this preferable to returning null when an activity or context cannot be found? And should I simply replace every getActivity() with requireActivity()?
requireContext() returns a nonnull Context , or throws an exception when one isn't available. If your code is in a lifecycle phase where you know your fragment is attached to a context, just use requireContext() to get a Context and also keep static analyzers happy about potential NPE issues.
requireActivity() a method that returns the non-null activity instance to fragment or throws an exception.
getContext() - Returns the context view only current running activity. getActivity()- Return the Activity this fragment is currently associated with. getActivity() can be used in a Fragment for getting the parent Activity of the Fragment .
Version 28(intended for Android Pie and below) is the last version of the legacy support library, so we recomand that you migrate to AndroidX libraies when using Android Q and moving forward. AndroidX replaces the original support library APIs with packages in the androidx namespace.
It is basically to have a method that always returns a non null object or throw an exception. That is all.
From the docs:
Fragments now have requireContext(), requireActivity(), requireHost(), and requireFragmentManager() methods, which return a NonNull object of the equivalent get methods or throw an IllegalStateException.
https://developer.android.com/topic/libraries/support-library/revisions.html#27-1-0
This SO question also references the reasons behind this:
"The getActivity and getContext methods return nullable types because when the Fragment is not attached to an Activity, these methods already returned null. There's no change in behaviour, it's just explicitly marked now, so you can safely handle it."
https://stackoverflow.com/a/47253335/3268303
From reddit:
"I updated from support v26 to support v27, and had to add a bunch of !!s to activity/context methods in Fragments where I obviously don't expect it to be null. Nice to have require* methods that do this for me without the ugly !!s."
https://www.reddit.com/r/androiddev/comments/80ork8/support_library_2710_has_been_released/duxp75h/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With