64

I have stored some data to a Global Class By using the Application Context In One Activity. Later I have to Retrieve those values in A Fragment. I have done something like this to store in Global Class.

AndroidGlobalClass  AGC = ((AndroidGlobalClass) getApplicationContext());
AGC.setUser_access("XYZ");
AGC.setFirst_name("ABC");

And In the Manifest I have done :

<application
    android:name=".AndroidGlobalClass"
    android:theme="@style/AppTheme" >
    <activity
       android:name="abc.SignInActivity"
       android:label="@string/app_name" >
       <intent-filter>
          <action android:name="android.intent.action.MAIN" />
          <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>
    </activity>
</application>

Now When I am Trying to Get the Application Context Using this... I am not getting the Context...

AndroidGlobalClass  AGC = ((AndroidGlobalClass) getApplicationContext());

This is My Fragment Activity

public class Fragment_NewsFeed extends Fragment {
    public Fragment_NewsFeed() {
    }

    RestImplimentationMethods RIM;
    AndroidGlobalClass AGC;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_newsfeed, container, false);
        return rootView;
    }
}
Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
NRahman
  • 2,717
  • 5
  • 24
  • 29
  • 9
    Be careful asking for help "ASAP". You scare off anyone who might want to give you a nice thorough answer. As you've seen you end up w/ a bunch of one line answers that don't really help. – tir38 Jul 30 '14 at 18:24
  • or use `isAdded()` to check weather fragment is attached to activity or not and if attached than u will able to get `getActivity().getApplicationContext()` :). this way u insure, never get NPE error and app will not gonna crash – Ashu Kumar Aug 02 '17 at 11:00

10 Answers10

206

You can get the context using getActivity().getApplicationContext();

SalGad
  • 2,991
  • 2
  • 18
  • 25
  • 45
    Careful where you're calling this, as `getActivity()` will return null if the fragment has been detached – gunar Dec 09 '13 at 07:10
  • 4
    Create a static application context in your Application class and assign it in onCreate(): MyApplication.sContext = getApplicationContext(); Then you can access it from any activity without worrying about fragment detachment. – Eduard Feb 23 '15 at 18:09
  • 9
    No need to use .getApplicationContext(), just getActivity() is enough. – Borzh Apr 06 '15 at 14:25
  • 1
    Only get `getApplicationContext()` when the object to which context has to be passed has a global context other wise be ready for OOM sooner or latter. – Mehvish Ali Dec 12 '16 at 20:35
  • 3
    @Borzh getActivity() will not give you the application context and will lead to memory leaks with retained fragments after activity recreation. It is not advisable to use that context if you don't specifically need it. It is always better to call getApplicationContext() if that is sufficient. – A. Steenbergen May 07 '17 at 11:38
20

Use

getActivity().getApplicationContext()

to obtain the context in any fragment

Aakash
  • 1,860
  • 19
  • 30
14

In Kotlin we can get application context in fragment using this

requireActivity().application
Eldhopj
  • 2,703
  • 3
  • 20
  • 39
  • 1
    The problem is requireActivity could throw an exception, not sure you want to cope with that. – David Jun 19 '22 at 23:19
4

you can define a global variable :

private Context globalContext = null;

and in the onCreate method, initialize it :

globalContext = this.getActivity();

And by that you can use the "globalContext" variable in all your fragment functions/methods.

Good luck.

Nabz
  • 390
  • 2
  • 14
  • When a fragment is detached, getActivity() returns null. A fragment is often detached during its own onCreate() while the activity is being recreated. This may crash with a NullPointerException after your app is pushed out of memory. Also, getActivity() does not return the application context. It requires another call to .getApplicationContext(). – colintheshots Mar 21 '18 at 14:21
  • @colintheshots, could a fragment be actually detached during its own onCreate() if this fragment is created in the activity's onCreate()? – Domosed Jul 04 '19 at 05:40
  • A fragment is typically attached during onCreate(). However, globalContext can later refer to an activity that no longer exists while detached or after being reattached. Also, it does not provide the Application Context, but the Activity context. – colintheshots Jul 06 '19 at 17:41
3

Try to use getActivity(); This will solve your problem.

Ashwin S Ashok
  • 3,623
  • 2
  • 29
  • 36
2

Pretty late response but you can do the following in Kotlin:

activity?.applicationContext?.let { SymptomsAdapters(it, param2, param3, ...) }

(?.) is for safe null operation to prevent from the null pointer exception.

You do not want to create a new context as that can lead to memory leaks when interchanging between fragments or when the device changes rotation.

And as someone mentioned above, in Java you can obtain context in a fragment by doing the following:

getActivity().getApplicationContext()
Qasim Wani
  • 111
  • 1
  • 5
0

In Support Library 27.1.0 and later, Google has introduced new methods requireContext() and requireActivity() methods.

Eg:ContextCompat.getColor(requireContext(), R.color.soft_gray)

More info here

Jithin Jude
  • 840
  • 14
  • 19
0

It's working for me

private Context contextUApp;

... OnCreate...

contextUApp = view.getContext();

or use

requireContext()
Victor Sam VS
  • 139
  • 3
  • 4
0

In Kotlin Fragment, onViewCreated, use

        val application = requireNotNull(this.activity).application

requireNotNull

is needed because the Fragment could be attached to a Context instead of a FragmentActivity. Alternatively, you could omit

requireNotNull

but then the code become

        val application = (this.activity)?.application

and the next application call must be accompanied by, for example

val dummy = application?.let {.......}

where "...." is your code.

Lucas
  • 458
  • 4
  • 6
-2

Add this to onCreate

// Getting application context
        Context context = getActivity();
Thiago
  • 12,778
  • 14
  • 93
  • 110
  • 6
    This is not the application context! Using this context with retained fragments across activity recreation will lead to memory leaks! – A. Steenbergen May 07 '17 at 11:36