Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to reuse Fragment after onDestroy() has been called?

I am using the Fragment class with the Android support library v7. In my Activity's onCreate() method I create a bunch of fragments and store them into properties of my activity.

this.firstFragment = new FirstFragment();
this.secondFragment = new SecondFragment();
// and so on

I use the navigation drawer pattern to switch between the fragments of my app. To change the active fragment I use following code.

// Replace the current content of the fragment holder with the selected section fragment.
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, selectedFragment).commit();

This results in a call to onDestroy() of the removed fragment. Is it safe to reuse the fragment after it's onDestroy() has been called, or should I recreate the fragment every time it is shown to the user.

This is a question of time vs. memory consumption, as at least one of the fragments needs some time to get created.

like image 924
david.schreiber Avatar asked Sep 10 '25 04:09

david.schreiber


1 Answers

onDestroy functionality is to destroy all the used variables and consumed memory. All those will be flagged as a Dummy data to enable the garbage collector to remove them from the memory whenever it is needed.

Calling the Fragment again after calling onDestroy will pass through the lifecycle again from the beginning through onCreate and all the variables and local object will be re-initialized again.

Is it Safe? Yes, it is safe.

You are thinking deeper to handle the lifeCycle of the Fragment that is already being handled by the OS.

If you want to prevent the Fragment from being destroyed you can create it as a static object.

like image 147
Sami Eltamawy Avatar answered Sep 12 '25 19:09

Sami Eltamawy