When to use the getActivity() in the fragment and when of requireActivity()
Is it better to use a requireActivity() instead of a getActivity()?
In fact, I want to avoid Null error
I use Java
When to use the getActivity() in the fragment and when of requireActivity()
Is it better to use a requireActivity() instead of a getActivity()?
In fact, I want to avoid Null error
I use Java
You can use requireActivity()
inside the scope of a fragment lifecycle. Inside fragment lifecycle, i.e. between onAttach()
and onDetach()
, you are sure that the activity is not null. But in case you are not sure the activity is non-null, i.e. inside a thread or callback, it's better to use getActivity()
with null check