0

Is it safe (correct) to simply return from method's and do nothing if context is null? currently I'm doing this when ever I need context from fragment.

Context context = getContext();
if(context == null) return;

My question is too stupid and obvious but I'm still not sure if this is correct. if its necessary or not. (maybe I should log warnings?)


I do this check in onCreateView, onViewCreated, when getting context from itemView in view holders and inside view click listeners when ever needed.

forpas
  • 160,666
  • 10
  • 38
  • 76
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118

2 Answers2

2

I think retrunning and doing nothing is as bad as catching an exception and swallowing it.

Fragment has a method requireContext(). It simply crashes the app when the context is null. Actually, I haven't never seen my app is crashed because of it. So I guess a null context in a fragment is a pretty rare and extreme case.

In the onViewCreated, you can also get context from the created view. It's non null because the view creation requires a context.

If you need some resources, you can also use getResources().getString() instead of getContext().getString()

Dewey Reed
  • 4,353
  • 2
  • 27
  • 41
  • Thanks, i think i can use `requireContext` for cases when im 100% sure its not null. like after `onAttach` is called as mentioned by @forpas – M.kazem Akhgary Dec 02 '18 at 14:43
1

Since your code is inside a fragment you must use:

getActivity()

to get the context of the host activity.
Why do you get null context?
After onAttach() you can use getContext()

forpas
  • 160,666
  • 10
  • 38
  • 76
  • I never get null context, its just that i dont know if it will ever be null or not, because return type nullable. and how should i handle that. – M.kazem Akhgary Dec 02 '18 at 14:17
  • If for every object we use in our code we write `if (obj != null)` then our classes would be filled with ifs and returns. If you know when every context is valid don't make so many checks. – forpas Dec 02 '18 at 14:21
  • Thanks, that's exactly what i want to know! when context is valid? – M.kazem Akhgary Dec 02 '18 at 14:24
  • 1
    See this link that mentions all about fragment lifecycle:https://google-developer-training.gitbooks.io/android-developer-advanced-course-concepts/content/unit-1-expand-the-user-experience/lesson-1-fragments/1-2-c-fragment-lifecycle-and-communications/1-2-c-fragment-lifecycle-and-communications.html – forpas Dec 02 '18 at 14:29
  • 1
    Anyway the standard is that after `onAttach()`, `getContext()` is valid. – forpas Dec 02 '18 at 14:32