Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;     } } 
like image 611
NRahman Avatar asked Dec 09 '13 06:12

NRahman


People also ask

How do I get an application inside a fragment?

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

Does fragment have context?

The fragment has different notifications, one of them being onActivityCreated. You can get the instance of the activity in this lifecycle event of the fragment. Then: you can dereference the fragment to get activity, context or applicationcontext as you desire: this.

What is requireContext?

requireContext() returns a nonnull Context , or throws an exception when one isn't available. If your code is in a lifecycle phase where you know your fragment is attached to a context, just use requireContext() to get a Context and also keep static analyzers happy about potential NPE issues.

What is application context in Android?

Definition. it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application).


2 Answers

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

like image 51
SalGad Avatar answered Oct 14 '22 03:10

SalGad


Use

getActivity().getApplicationContext()

to obtain the context in any fragment

like image 44
Aakash Avatar answered Oct 14 '22 02:10

Aakash