M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

What to do when context is null in fragment

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.

Upvotes: 0

Views: 2516

Answers (2)

forpas
forpas

Reputation: 164099

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()

Upvotes: 1

Dewey Reed
Dewey Reed

Reputation: 4956

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()

Upvotes: 3

Related Questions