简体   繁体   中英

Android/Java: Fragment instantiating causes memory leak?

My MainActivity has a Drawer and instantiates a new Fragment , depending on the clicked MenuItem (based on this tutorial ).

I monitored the memory , which is slightly increasing on every Fragment change and I worry, that fragmentClass.newInstance() is not the right way.

// MainActivity
public boolean onNavigationItemSelected(MenuItem item) {

    int id = item.getItemId();
    Fragment fragment = null;
    Class fragmentClass = null;
    if (id == R.id.nav_camera) {
        fragmentClass = CameraFragment.class;
    } else if (id == R.id.nav_gallery) {
        fragmentClass = GalleryFragment.class;
    } else if (id == R.id.nav_slideshow) {
        fragmentClass = SlideshowFragment.class;
    } else if (id == R.id.nav_manage) {
        fragmentClass = ManageFragment.class;
    } else if (id == R.id.nav_share) {
        fragmentClass = ShareFragment.class;
    } else if (id == R.id.nav_send) {
        fragmentClass = SendFragment.class;
    }

    try {
        fragment = (Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.layout_main, fragment).commit();
}

I would expect something like:

// Pseudocode
if (fragmentManager.instanceExists(fragmentClass)) {
    // load instantiated fragment
} else {
    // newInstance()
}

How could I avoid memory leaks or is this even related?

Thank you!

Practically, there is no problems in that code. Things you can optimize are:

  1. Reworking Fragment#instantiate() method (check docs )
  2. Caching instances in something like Map in order not to create the new one every time you navigate through the drawer

Also, you can check if fragment exists in FragmentManager using FragmentManager#findFragmentById() or FragmentManager#findFragmentByTag()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM