Why did he recommend not saving the fragment with the user interface?

I read that a persistent snippet with ui and links to views can cause a memory leak. Than I create a test application with a fragment, where I store some links to the views and set setRetaineInstance (true), but a few screen rotations do not cause any leaks. MAT says that I have only one instance of parent activity. What am I doing wrong? In what cases can saving a fragment with ui lead to leaks?

RetainInstanceActivity.java

public class RetainInstanceActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(android.R.id.content, RetainFragment.newInstance()) .commit(); } }} 

RetainFragment.java

 public class RetainFragment extends Fragment { private View mLogin; private View mPassword; private View ImageView; public static RetainFragment newInstance() { final RetainFragment fragment = new RetainFragment(); return fragment; } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment_retain, container, false); mLogin = view.findViewById(R.id.login); mPassword = view.findViewById(R.id.password); ImageView = view.findViewById(R.id.img); return view; } 

}

+7
android memory-leaks android-fragments
source share
1 answer

Here you keep references to the old activities of mLogin, mPassword and ImageView, but they are overwritten immediately after rotation, as onCreateView () will be called, therefore, if your activity is a front-line activity and configuration changes occur, you should be fine.

You may encounter memory leaks if, if your activity is not the main activity, and, in general, you cannot know how your fragment is processed.

For example, ViewPager has 2 different adapters, one ( http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html ) saves instances of the fragment (just calls onDestroyView ()), and the other (FragmentStatePagerAdapter) destroys instances of a fragment.

Thus, your fragment will lose significant memory if used with the FragmentPagerAdapter.

I hope this is an example of potential problems. If you know what you are doing, then there is no problem calling setRetaineInstance (true) and not deleting the views.

+7
source share

All Articles