Get the Application Context In Fragment In Android

2019-01-16 08:07发布

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

5条回答
Evening l夕情丶
2楼-- · 2019-01-16 08:35

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.

查看更多
Fickle 薄情
3楼-- · 2019-01-16 08:36

Use

getActivity().getApplicationContext()

to obtain the context in any fragment

查看更多
Emotional °昔
4楼-- · 2019-01-16 08:46

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

查看更多
够拽才男人
5楼-- · 2019-01-16 08:59

Add this to onCreate

// Getting application context
        Context context = getActivity();
查看更多
闹够了就滚
6楼-- · 2019-01-16 09:00

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

查看更多
登录 后发表回答