When to use the getActivity() in the fragment and when of requireActivity()
Is it better to use a requireActivity() instead of a getActivity()?
In fact, I want to avoid Null error
I use Java
You can use requireActivity() inside the scope of a fragment lifecycle. Inside fragment lifecycle, i.e. between onAttach() and onDetach(), you are sure that the activity is not null. But in case you are not sure the activity is non-null, i.e. inside a thread or callback, it's better to use getActivity() with null check
Related
What is the difference between requireActivity() and requireContext() when starting a new Activity Intent
startActivity(Intent(requireContext(), A::class.java))
startActivity(Intent(requireActivity(), B::class.java))
A Fragment theoretically can be attached to a Context that is not an Activity. In this case requireActivity() would throw an Exception when requireContext() wouldn't.
You would know if you were using a Fragment in this unconventional way, so for all intents and purposes, there is no practical difference.
requireContext() is returning the same Activity instance as requireActivity() would, but it is upcast to Context. An Activity would be implicitly upcast to Context anyway when you pass it to the Intent constructor, since it is expecting a Context.
requireActivity() a method that returns the non-null activity instance to fragment or throws an exception. If you are 100% sure that in your fragment's lifecycle, activity is not null
requireContext() returns a nonnull Context , or throws an exception when one isn't available.
I must call getActivity in my fragment. I have read on Stackoverflow e.g. that we could store the activity in a class/object attribute, but I have read that it's a bad practice too.
Would it be possible to override onActivityCreated in the fragment, and simply execute all my logic (which requires getActivity) in this callback?
It should avoid any NullException.
I would say use a WeakReference to your activity, you can use it to access the activities members from a fragment
https://developer.android.com/reference/java/lang/ref/WeakReference
In the documentation of the android.support.v4.app.Fragment class (not the framework's class) for the getActivity() method stated that the returned value may be null if the Fragment is associated with a Context.
How an Fragment can be associated with a Context? Is not the FragmentManager the only way to attach an Fragment to something? But the FragmentManager can be obtained only from Activity. Or not?
How an Fragment can be associated with a Context?
You must have heard of FragmentHostCallback. If you haven't check out the link.
In a simple way, it is an integration point with a Fragment Host. When I say Fragment Host, It is an object that can hold Fragments. For example an Activity. In order to host a fragment - one must implement FragmentHostCallback.
However, I haven't come up with any ideas about how Fragment can be implemented in non-activity objects. Will see in future may be...
So that way, getActivity() will return null on non-activity objects.
PS,
Always go for getContext() if you are requiring context rather than activity
As I understand, you need the context inside of a fragment.. If so have you checked the method getContext() method inside of a fragment?
Also getActivity() can be null if you are referencing it when the fragment is not attached to an activity. Have a check of the fragment lifecycle to learn more.
Hope I helped
I'm using fragments in my application. And the very common problem while using them are the NPE when using getActivity(). I know we can solve it by checking if getActivity() != null every single time or checking if the fragment isAdded().
In one of my classes I'm getting activity's context in more than 60 places. Checking if getActivity()is not null or if the fragment is still added to the activity in all the places is making the code ugly,larger and non-maintainable. Is there any other way to handle this?
Is it even possible to destroy the fragment(and stop any work it has been doing while being removed) when it is removed from the activity?
Also Is this way a suggested one?
In my experience, most cases of getActivity() returning null are in asynchronous callbacks.
For example, your fragment fires an AsyncTask, and then gets removed before the the background job is done, then when the background job finishes and calls getActivity() in onPostExecute(), it will get a null since the fragment is already detached from the activity.
My solution:
1.Check getActivity()==null at the beginning of every asynchronous callback, if it's the case then just abort the method.
2.Cancel asynchronous jobs in onDetach().
And I think this is a better solution than saving the activity instance in onAttach(), because since your fragment is removed, why bother doing all the jobs left in the callbacks(in most cases UI codes)?
getActivity will be reinitilized in method - onActivityCreated().
So it's safer to call getActivity() right after onActivityCreated() (according to lifecycle of fragments http://developer.android.com/guide/components/fragments.html) - for example in onStart() - in that case it's WILL BE NEVER NULL - no need to do useless checks like isAdded and getActivity != null.
P.S. If we use that solution:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
mActivity will be never null - but later in method onActivityCreated() getActivity() became different with mActivity.
My opinion - sure we can save whole activity in variable, but it's safer to follow android fragments lifecycle workflow and get activity right after onActivityCreated()
I think you should use the Fragment's onAttach(Activity) method.
I think that should help you avoid all of those NPE.
My solution is override the onSaveInstanceState method in BaseActivity:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//solution of fragment.getActivity() is null
outState.remove("android:support:fragments");
}
I didn't found a solution to that, maybe because if you think about the lifecycle of a fragment you should be able to understand when you have check the null value.
taken from http://developer.android.com/guide/topics/ui/settings.html:
Note: A PreferenceFragment doesn't have a its own Context object. If
you need a Context object, you can call getActivity(). However, be
careful to call getActivity() only when the fragment is attached to an
activity. When the fragment is not yet attached, or was detached
during the end of its lifecycle, getActivity() will return null.
If I call getActivity() from within the OnCreate() method of a PreferenceFragment then can I be assured that the fragment is attached to its activity - or is there some other way you should get the Context in this instance?
The reason I need a Context is I'm trying to use a Toast notification from the PreferenceFragment
If you want to make sure that a Context is available you'll need to wait until the Fragment has been attached to an Activity. The callback for this is the onAttach(Activity) method.
Depending on the lifecycle state of your fragment the getActivity() method can also return null.