Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get application object into fragment class

People also ask

How do I get an application inside a fragment?

Use appCtx = (UnityMobileApp) getActivity(). getApplication(); in your fragment. Show activity on this post. The method getActivity() may have possibility to return null.

How can I move from activity to fragment?

A fragment is Attached to an activity, you can Add a fragment or Replace a fragment with FragmentTransition. Note that a fragment need an activity to exist ! You don't go from activity to fragment... But if you are in an activity that contain a fragment you can open a new activity on top of the first.

How do you create a fragment object?

Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.


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


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.


As you are trying yo use application context from fragment you can not use getApplication() because that isn't method of Fragment class
So you first have to use the getActivity() which will return a Fragment Activity to which the fragment is currently associated with.

to sumup in your code,

instead of this.getApplication() you have to use getActivity.getApplication()

know more about getActivity() from android documentation


Alternatively using Kotlin

fun bar() {
   (activity?.application as UnityMobileApp).let {
      it.drink()
   } ?: run {
      Log.d("DEBUG", "(╯°□°)╯︵ ┻━┻")
   }
}

A Newer way:

Application application = requireActivity().getApplication();