'use requireActivity() or getActivity() in fragment

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



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bibaswann Bandyopadhyay