gabin February 2016

RecyclerView leaks in FragmentPagerAdapter

I've figured out that in defined concatenation of circumstances RecyclerView leads to memory leak. To archive such effect, I have created FragmentPagerAdapter that contains fragment with RecyclerView as child. In case of going application to background or finishing, leak canary fires memory leak alert. Here's my activity class

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    ViewPager mViewPager = (ViewPager) findViewById(R.id.view_pager);
    List<Fragment> fragments = new LinkedList<>();
    for (int i = 0; i < 10; i++) {
        fragments.add(CustomFragment.newInstance(i));
    }

    mViewPager.setAdapter(new CustomPagerAdapter(getFragmentManager(), fragments));
    mViewPager.setCurrentItem(0, false);
}

  public class CustomPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;

    public CustomPagerAdapter(FragmentManager fragmentManager, List<Fragment> fragments) {
        super(fragmentManager);
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }
  }
}

To get the leak, RecyclerView even doesn't need to be initialized. If I comment it in xml file, the leak isn't fired

public class CustomFragment extends Fragment {

public static final String POSITION = "position";

public static CustomFragment newInstance(int position) {
    Bundle b = new Bundle();
    b.putInt(POSITION, position);
    CustomFragment fragment = new CustomFragment();
    fragment.setArguments(b);
    return fragment;
}

private int position;
private RecyclerView         

Answers


bluebyte February 2016

Your stack trace shows at least two things:

  1. It is not RecyclerView who leaks activity. It is the ImputMethodManager.
  2. LEAK CAN BE IGNORED. According to Leak Canary docs it is a known sdk problem. But I don't think its really an activity leak. If you check your memory dump you will not see several activity instances. Code looks pretty safe at now.

Post Status

Asked in February 2016
Viewed 2,089 times
Voted 14
Answered 1 times

Search




Leave an answer