What is the purpose of requireActivity() and requireContext() in Fragment?
Because they might be null. In java you can just call for them. But in Kotlin they are declared as nullable return types. So you have 3 options:
Check the official Android Source code documentation. Those methods return activity/context with a null check.
requireActivity()
public final FragmentActivity requireActivity() {
FragmentActivity activity = getActivity();
if (activity == null) {
throw new IllegalStateException("Fragment " + this + " not attached to an activity.");
}
return activity;
}
requireContext()
public final Context requireContext() {
Context context = getContext();
if (context == null) {
throw new IllegalStateException("Fragment " + this + " not attached to a context.");
}
return context;
}
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