Reputation: 3509
Activity has isDestroyed(), but I can't find the counterpart for Fragment.
I could override onDestroyed() to set a flag for myself but I assume there's an existing solution.
I'm trying to check whether a fragment is destroyed or not in a network response before updating UI in the fragment.
Any help will be greatly appreciated. Thanks!
Upvotes: 21
Views: 10775
Reputation: 607
Since all fragments are destroyed if the activity is destroyed, a simple answer could be calling getActivity().isDestroyed()
returning true if the activity is destroyed, therefore the fragment is destroyed. Nesting fragments is generally not a good idea.
You could also override the fragments onDestroyView()
method checking and setting boolean variable to true
Upvotes: 2
Reputation: 53600
You can create a Fragment as your parent of other fragments and use following code to check is destroyed functionality.
public abstract class ASafeFragment extends Fragment
{
protected boolean isSafe()
{
return !(this.isRemoving() || this.getActivity() == null || this.isDetached() || !this.isAdded() || this.getView() == null);
}
...
}
or
public static boolean isSafeFragment( Fragment frag )
{
return !(frag.isRemoving() || frag.getActivity() == null || frag.isDetached() || !frag.isAdded() || frag.getView() == null );
}
Upvotes: 37
Reputation: 317692
The most bulletproof pattern to decide how to deal with work that may be in progress is to put that work in a Loader. The LoaderManager for the fragment/activity will be smart about invoking your LoaderCallbacks only when it's an appropriate time to handle those results, or possibly even retain the results for a replacement fragment/activity after a configuration change. It's extra coding, but it's the best way to recover from interruption and cancellation.
Upvotes: 0
Reputation: 3654
From developer site: "when the activity is destroyed, all fragments will be destroyed." All fragmetns are contained in an activity so you should check your activity.
There is no isDestroyed() for fragments
Upvotes: -1
Reputation: 7070
I'm trying to check if a fragment is destroyed or not in a network response, to decide whether to update UI components.
You can use onDestroyView()
because UI update is not possible after onDestroyView()
gets called since UI gets destroyed.
Before doing any UI update , you can check if getActivity()
is null
or not.
Upvotes: 0