What I do is
Approach 1:
public View onCreateView(.....){
context = getContext();
}
I am using this context object wherever I need. Is this the right approach or I should use getContext != null
and use the value returned by getContext()
. Also I understand that I can get the context from getActivity()
but it will also return null if 'getContext()' is returning null.
As an alternative I can do this every time I need the context.
Approach 2:
if(getActivity() != null){
//use getActivity() here
}
I want to understand which one is a better way and why?
getActivity()
Context
as local variable can be harmful because,Fragment
has it's own lifecycle and we can't predict at which stage context becomes null (getActivity()
orgetContext()
).