Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Fragment recovery in Android

We are using Fragments and we don't need them to be automatically recovered when the Activity is recreated. But Android every time when Activity::onCreate(Bundle savedInstanceState) -> super.onCreate(savedInstanceState) is called, restores Fragments even if we use setRetainInstance(false) for those Fragments.

Moreover, in those Fragments Fragment.performCreateView() is called directly without going through Fragment::onAttach() and so on. Plus, some of the fields are null inside restored Fragment...

Does anybody know how to prevent Android from restoring fragments?

P.S. We know that in case of recreating Activity for config changes it could be done by adding to manifest android:configChanges="orientation|screenSize|screenLayout. But what about recreating activity in case of automatic memory cleaning?

like image 941
goRGon Avatar asked Mar 20 '13 09:03

goRGon


People also ask

How do you stop a fragment from recreating?

Calling setRetainInstance(true) will prevent the Fragment from being re-created. But, right now the Activity is always re-creating the DrawerFragment and forcefully re-creating the HomeFragment , resulting in the behavior you are seeing. In your Activity. onCreate() check the savedInstanceState is null .

What is fragmentation in Android Studio?

A Fragment represents a reusable portion of your app's UI. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. Fragments cannot live on their own--they must be hosted by an activity or another fragment.


2 Answers

We finished by adding to activity:

@Override public void onCreate(Bundle savedInstanceState) {     super.onCreate(null); } 

It suppresses any saved data on create/recreate cycle of an Activity and avoids fragments auto re-creation.

like image 157
goRGon Avatar answered Sep 16 '22 21:09

goRGon


@goRGon 's answer was very useful for me, but such use cause serious problems when there is some more information you needs to forward to your activity after recreate.

Here is improved version that only removes "fragments", but keep every other parameters.

ID that is removed from bundle is part of android.support.v4.app.FragmentActivity class as FRAGMENTS_TAG field. It may of course change over time, but it's not expected.

@Override public void onCreate(Bundle savedInstanceState) {     super.onCreate(createBundleNoFragmentRestore(savedInstanceState)); }  /**  * Improve bundle to prevent restoring of fragments.  * @param bundle bundle container  * @return improved bundle with removed "fragments parcelable"  */ private static Bundle createBundleNoFragmentRestore(Bundle bundle) {     if (bundle != null) {         bundle.remove("android:support:fragments");     }     return bundle; } 
like image 41
Menion Asamm Avatar answered Sep 17 '22 21:09

Menion Asamm