Home Ask Login Register

Developers Planet

Your answer is one click away!

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 {

protected void onCreate(Bundle savedInstanceState) {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    ViewPager mViewPager = (ViewPager) findViewById(R.id.view_pager);
    List<Fragment> fragments = new LinkedList<>();
    for (int i = 0; i < 10; 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) {
        this.fragments = fragments;

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

    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();
    return fragment;

private int position;
private RecyclerView         


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


Leave an answer

Quote of the day: live life