What to do when context is null in fragment

半世苍凉 提交于 2019-12-22 01:18:23

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/53580907/what-to-do-when-context-is-null-in-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!