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 t
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
You can get the context using
getActivity().getApplicationContext();
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()
Add this to onCreate
// Getting application context
Context context = getActivity();
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.