How to get application object into fragment class

The method getActivity() may have possibility to return null. This may crash your app.So it is safe to use that method inside the onActivityCreated(). Eg:

private UnityMobileApp appCtx;
.
.
...
@Override
public View onCreateView(...){
...
}

@Override public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     appCtx = ((UnityMobileApp) getActivity().getApplication()); 
} 
...
//access the application class methods using the object appCtx....

This answer is derived from Dzianis Yafima's answer asked by Ognyan in comments. Thus the Credit goes to Dzianis Yafima's and Ognyan in stackoverflow.


Use appCtx = (UnityMobileApp) getActivity().getApplication(); in your fragment.