[android] Get the Application Context In Fragment In Android?

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;
    }
}

This question is related to android android-fragments fragment

The answer is


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


Add this to onCreate

// Getting application context
        Context context = getActivity();

Use

getActivity().getApplicationContext()

to obtain the context in any fragment


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()

In Kotlin we can get application context in fragment using this

requireActivity().application

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.


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


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-fragments

FragmentActivity to Fragment How to start Fragment from an Activity How to use data-binding with Fragment In android how to set navigation drawer header image and name programmatically in class file? Android Fragment onAttach() deprecated How to convert any Object to String? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments java.lang.IllegalStateException: Fragment not attached to Activity java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

Examples related to fragment

FragmentActivity to Fragment Handling back button in Android Navigation Component android.content.Context.getPackageName()' on a null object reference Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment How to move from one fragment to another fragment on click of an ImageView in Android? Android - save/restore fragment state Intent from Fragment to Activity Get the Application Context In Fragment In Android? Add Items to ListView - Android Using onBackPressed() in Android Fragments