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; } }
Use appCtx = (UnityMobileApp) getActivity(). getApplication(); in your fragment. Save this answer.
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.
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.
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).
You can get the context using getActivity().getApplicationContext();
Use
getActivity().getApplicationContext()
to obtain the context in any fragment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With