Get the Application Context In Fragment In Android?

NRahman picture NRahman · Dec 9, 2013 · Viewed 120.8k times · Source

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

Answer

SalGad picture SalGad · Dec 9, 2013

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