63

I am changing my android mobile app to support both tablets and mobile phone. For this I am changing my activity class into fragment. In my activity class I have an instance of my application class created as below:

appCtx = (UnityMobileApp) getApplication();

Where UnityMobileApp is my Application class.

Now I want to create the same instance in my fragment class. Can you guys please help me solve this?

jnthnjns
  • 8,962
  • 4
  • 42
  • 65
Rakesh Gourineni
  • 1,361
  • 5
  • 16
  • 30

6 Answers6

145

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

biegleux
  • 13,179
  • 11
  • 45
  • 52
  • 23
    Please note that in some cases above code will throw NPE because it may get called in a situation where `getActivity()` will return null (e.g. in the middle of rotation for example) – Ognyan Jul 21 '13 at 10:34
  • 10
    Use it in: @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); app = ((MyApplication) getActivity().getApplication()); } – Dzianis Yafimau Feb 13 '15 at 21:19
4

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.

BharathRao
  • 1,846
  • 1
  • 18
  • 28
4

If someone is looking for a Kotlin version. This works for me:

(activity?.application as YourApplicationClass)
clauub
  • 1,134
  • 9
  • 19
1

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

Shankar
  • 2,890
  • 3
  • 25
  • 40
1

Alternatively using Kotlin

fun bar() {
   (activity?.application as UnityMobileApp).let {
      it.drink()
   } ?: run {
      Log.d("DEBUG", "(╯°□°)╯︵ ┻━┻")
   }
}
Alex Nolasco
  • 18,750
  • 9
  • 86
  • 81
1

A Newer way:

Application application = requireActivity().getApplication();
hata
  • 11,633
  • 6
  • 46
  • 69