Finally I came up with this solution for my Fragments
, and I did not get any error since:
I will actually get the context for the Fragment
as soon as possible, in the method onAttach()
:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity;
}
Thanks to this, I can use the Activity
's context anywhere in the class.
For the cases where I need to get elements from the Activity
itself, I will do it in the method onActivityCreated()
that guarantees that the Activity
will be fully initialized.
For example:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Get the device screen size
Display display = getActivity().getWindowManager().getDefaultDisplay();
(...)
}