I want to replace fragment and destroy previous.
Here my code :
FragmentManager manager = getFragmentManager();
FragmentTransaction newT = manager.beginTransaction();
newT.replace(R.id.activity_content currentFragment, CE_TAG);
newT.commit();
I read this article : http://sapandiwakar.in/replacing-fragments/
I've not put the fragment in back stack, but my fragement are not destroyed !
onPause(), onDestroy(), onStop() are never called.
Thanks.
Try
Fragment f = new YOurFragment();
fragmentTransaction.remove(f).commit();
Hope it helps
A fragment is maintained in memory even after it is no longer visible. If you call it back into existence, onCreateView is called and the visual part of the fragment is recreated but the actual object is reused. From the Docs:
onDestroy() = The final call you receive before your activity is
destroyed. This can happen either because the activity is finishing
(someone called finish() on it, or because the system is temporarily
destroying this instance of the activity to save space. You can
distinguish between these two scenarios with the isFinishing() method.
You should consider onDestroyView instead, or call finish if that suits you better.
http://developer.android.com/reference/android/app/Fragment.html
Try adding this line of code after committing the transaction.
getChildFragmentManager().executePendingTransactions();
Check this executePendingTransactions.
If you are replacing a fragment with the same tag, it may cause the issue of overlaping. Also, if your fragment container is a LinearLayout, it cannot update after replace (from my experience only).
Related
Is there any way, how to clear backStack of support FragmentManager without calling onCreateView() in stored fragments?
I understand fragment lyfe cycle and calling onDestroyView() and onCreateView() when it is popped.
http://developer.android.com/guide/components/fragments.html#Creating
Also I know how to pop all fragments from backstack with
mFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
or
for(int i = 0; i < mFragmentManager.getBackStackEntryCount(); ++i) {
mFragmentManager.popBackStack();
}
but both ways are calling onCreateView() and other lyfe cycle methods until to onDestroyView() and onDestroy().
But is there any way, how to clear this backstack with calling only from onDestroyView() and not from onCreateView() (inside of fragments)?
Or is there any way how to do replace transaction with clearing previous fragments?
For example, I want clear backstact before I do transaction:
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().replace(R.id.content, fragment).commit();
I haven't found a simple solution to this issue. I'm almost certain there is no feature of FragmentManager or Fragment that allows you to control which lifecycle method are called when a fragment is popped from the stack. I'll outline two possible approaches. Each has some undesirable aspects.
The first approach assumes the fragments you are popping out of the backstack are children of an activity. If they are children of a fragment, the method still applies, just a different type of parent object.
Add a boolean member mClearingBackStack to the activity (or parent fragment) with a getter method. Set the boolean only when you are starting a complete clear of the backstack. In the fragment lifecycle methods where you want to disable processing, get the flag and modify the processing accordingly. For onCreateView() through onDestroyView(), the fragment will be attached and the host activity available with getActivity(). Cast it to whatever your activity class is to use the flag's getter method.
Because popBackStack() is asynchronous, clearing the flag must be done only after the stack unwinding completes. I haven't tried it, but I think posting a Runnable after calling popBackStack() to clear the flag should work. Because the Runnable needs to go at the end of the queue, View.post() must be used instead of Activity.runOnUiThread(). An alternative is to call executePendingTransactions() to wait for the stack unwinding to complete.
The second approach is cleaner, if your design can accommodate it. Create a place-holder fragment that is a child of your activity and parent to all your other fragments. For all the fragment transactions you have now, use the new fragment's FragmentManager, obtained using getChildFragmentManager(). When you want to clear all those transactions, instead of popping the child fragment manager's stack, remove or replace the parent fragment in the activity's fragment manager. When the parent fragment is removed, all of its children are destroyed and go through the teardown steps, onDestroyView(), onDestroy(), etc. but not all the steps that would occur if its backstack were unwound. This approach is much simpler and more maintainable than the first, but requires you to rework your fragment hierarchy. An additional problem with this approach is that you must add some code to handle the Back action with a fragment hierarchy. The problem and various solutions are described here.
Now I have a fragment to do something will last long time. In some case , the activity will call onSaveInstanceState when fragment is still running. After fragment do all the things , I want to close it. Here will throw an exception Can not perform this action after onSaveInstanceState.
I know what it means, but I really need to close the fragment after something has been done. So if I use commitAllowingStateLoss to force fragment to close , after activity recreate, the close state won't be recreated, the UI will be broken.
So how should I close the fragment correctly ?
I don't know any safe way to automatically close fragment, and it seems like a bad idea (why would you depend on the system for this?). You will have to time it correctly in your app. I can give you code suggestion to do it. Since there is no close method, you use remove method instead, or popBackStack. Since you did not post any code, I am suggesting a generic way to do this.
Code suggestion using remove:
Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
...
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
transaction.remove(fragment);
transaction.commit();
Notes:
TAG_FRAGMENT is the ID for the fragment in the layout.
findFragmentByTag() is one way, another is new myFragment();
If you need to time when the Fragment is closed, use onDetach() override method of Fragment.
Update:
I think the leak is coming from getActivity().getSupportLoaderManager().restartLoader(getLoaderId(), null, this);
where i have my object implement LoaderCallback. Is there a way for me to clear the callback i tired setting it to
getActivity().getSupportLoaderManager().restartLoader(getLoaderId(), null, null);
but this crashes
Orig:
I have a list of objects in one of my fragments(A). When I navigate forward I add fragment A to the backstack. After I have navigated to a new fragment and I dump the heap. I still see my object in the heap. When I get the shortest path in the dump it looks like below. I can see that in FragmentManagerImpl there is a reference to fragment A in mActive fragments which is keeping my lists object alive.
Is my fragment supposed to stay in mActive fragments or is this a leak?
Adding to backstack
FragmentTransaction transaction = mFragmentManager.beginTransaction();
updateTransactionWith(info.getReplacement(), transaction, "replace");
transaction.addToBackStack(info.getReplacement().getClass().toString());
transaction.commit();
mFragmentManager.executePendingTransactions();
By calling addToBackStack(), you're requesting the FragmentManager that the Fragment being replaced be just stopped and not destroyed because you're either anticipating that a back button press is very likely or, the Fragment is heavy on initialization and you would still like to avoid doing it again even though the user is not very likely to go back.
The docs clearly state that
If you do not call addToBackStack() when you perform a transaction
that removes a fragment, then that fragment is destroyed when the
transaction is committed and the user cannot navigate back to it.
Whereas, if you do call addToBackStack() when removing a fragment,
then the fragment is stopped and will be resumed if the user navigates
back.
Hence, it's not a memory leak and your observations are quite in line with the expected behaviour.
However, just like an Activity, the system may still choose to destroy this Fragment, if it's running out of memory. But, that's expected behaviour too.
It's not a memory leak. You need to decide how to deal with your fragment's state.
Ideally you implement onSaveInstanceState and onViewStateRestored saving your state to the bundle and restoring it from the bundle respectively.
Alternatively, if you're able to re-create your state easily, you may want to save the bother of (re)storing it using the bundle and just null your references in the onPause method and create them during the onResume method. Be aware that onResume gets called even if the fragment has just been created, so be careful not to do that work more than once.
Either way, be sure to null your references to ensure your objects are marked for GC.
The FragmentManager will decide if it needs to discard and recreate the fragment as necessary in order to allow the user to go back to the fragment you added to the stack. In conditions where there's very little else on the stack and/or there's lots of spare memory it will probably just keep a direct reference to the fragment you added to the back stack.
Given all that, you also need to be careful about keeping references to other fragments, activities, etc as that kind of state is difficult to recreate.
The following approach is recommended for providing proper back navigation:
// Works with either the framework FragmentManager or the
// support package FragmentManager (getSupportFragmentManager).
getSupportFragmentManager().beginTransaction()
.add(detailFragment, "detail")
// Add this transaction to the back stack
.addToBackStack()
.commit();
More info:
http://developer.android.com/guide/components/fragments.html
http://developer.android.com/training/implementing-navigation/temporal.html
API docs: http://developer.android.com/reference/android/app/Fragment.html
I have a support library fragment that sends a network call, and recreate() the parent activity when it receives a specific network response. I can see that the activity does get recreated as I can see the onCreate() and onDestroy() are called.
But after the activity is recreated, the fragment is still there and it got stuck in a loop which keep recreating and making new fragments.
Here's part of the onCreate() of the activity:
if (someLogic()) {
fragmentA = new FragmentA();
FragmentUtil.addFragment(getSupportFragmentManager(), fragmentA);
} else {
fragmentB = new FragmentB();
FragmentUtil.addFragment(getSupportFragmentManager(), fragmentB);
}
FragmentA is the one that does the network call, and FragmentB is the fragment that should be displayed after the recreate(). When I check the list of fragments with getSupportFragmentManager().getFragments() I see 1 instances of FragmentA, and 16 instances of FragmentB.
My question is why does this happen, and how do I fix it?
Calling recreate() essentially causes the Activity to go through a configuration change. A configuration change causes both the Activity and its Fragments to be destroyed and recreated. So your Fragments should in fact be destroyed when this occurs (you can see for yourself by adding a Log message in your fragment's onDestroy method).
The fact that configuration changes cause fragments to be destroyed and created however does not mean that the FragmentManager will simply forget the fragments ever existed. The FragmentManager will still hold a reference to the newly created fragment after the configuration change occurs.
One thing you can do to prevent multiple fragments from being created is by doing something like this in your activity's onCreate():
if (savedInstanceState == null) {
// The Activity is being created for the first time, so create and
// add new fragments.
} else {
// Otherwise, the activity is coming back after being destroyed.
// The FragmentManager will restore the old Fragments so we don't
// need to create any new ones here.
}
I had same situation as #spy wrote, recreating the Activity after Day/Night mode is changed. Activity had four Fragments which they get restored after Activity.recreate() is called, because FragmentManager saves them as #Alex Lockwood stated. But restoring and not adding Fragments after recreation does not help me because of some architectural reasons of project, i wanted them to disappear.
Solution is to delete Fragments from FragmentManager just before Activity.recreate()is called, in my case it is in Activity.onStart():
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragmentA = fragmentManager.findFragmentByTag("fragmentATag");
if(fragmentA != null)
fragmentTransaction.remove(fragment);
// Find and delete other Fragments
fragmentTransaction.commit(); // or commitAllowingStateLoss()
recreate();
This way you will not get Fragments restored when Activity.onCreate() is called.
I am trying to implement a method where I want to return to the previous fragment and destroy the current one. However, when I add the fragment to the Backstack it doesn't get destroyed anymore afterwards.
Is there any way to destroy it? Or maybe to return to the previous fragment without using the Backstack?
Edit:
I want to use the backwards navigation as well.
Firstly if you are using the BackStack, it is not typical to need to specifically manually remove Fragments, which suggests you might want to have another think about your design.
That said, to specifically manually remove a Fragment, Override onBackPressed in your Activity which is showing the Fragments, manually remove the Fragment there.
To make it easy to determine which Fragment is currently showing, you can give it a Tag when you show it. For example:
fragTrans.replace(android.R.id.content, myFragment, "MY_FRAGMENT_X");
Then in the onBackPressed function of your Activity
#Override
public void onBackPressed()
{
FragmentManager fragMan = getFragmentManager();
// Check if that Fragment is currently visible
MyFragment myFragment = (MyFragment)fragMan.findFragmentByTag("MY_FRAGMENT_X");
boolean myFragXwasVisible = myFragment.isVisible();
// Let the Activity pop the BackStack as normal
super.onBackPressed();
// If it was your particular Fragment that was visible...
if (myFragXwasVisible)
{
FragmentTransaction trans = fragMan.beginTransaction();
trans.remove(myFragment).commit();
}
}
Note: When it comes to specifically destroying your Fragment object, that is what Java's garbage collection is for. You don't need to worry about that yourself, Java will take care of destroying it when it needs to. That's the whole point.