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
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.
Source: Stackoverflow.com