3

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

alkkhu
  • 53
  • 5
  • 1
    Does this answer your question? [What is the difference between requireActivity and onActivityCreated](https://stackoverflow.com/questions/61045573/what-is-the-difference-between-requireactivity-and-onactivitycreated) – Shehata Gamal Aug 01 '21 at 13:22
  • 3
    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 those methods, for example, IO callback, it's better to use `getActivity()` and check null + check destroyed. – Tuan Chau Aug 01 '21 at 13:35

1 Answers1

2

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

Bibaswann Bandyopadhyay
  • 3,389
  • 2
  • 31
  • 30