1

I have a viewpager with multiple types of pages (images, videos), so I used FragmentPagerAdapter.

The problem now is, when I have around 14 pages (mostly images) I get an outofmemory error when sliding to the latter ones. I can see a memory leak when changing pages since memory usage only increases and never goes down.

I tried reimplementing the onDEstroyItem method as suggested in other posts, but this seems to work with views instead of Fragments.

What should I do?

MichelReap
  • 5,630
  • 11
  • 37
  • 99

1 Answers1

5

You should use FragmentStatePagerAdapter instead of FragmentPagerAdapter as mentioned here. Also try to decrease the value set by setOffscreenPageLimit as mentioned.

Community
  • 1
  • 1
Yaroslav Mytkalyk
  • 16,950
  • 10
  • 72
  • 99
  • Thanks, I tried that but I keep getting the same error, even when setting setOffScreenPageLimit to 0. It's like there's a memory leak, but I never pass any reference to my Fragments. – MichelReap Feb 06 '13 at 14:12
  • Nope, it was my fault. I was somehow holding up a reference to the fragments. My bad. – MichelReap Feb 06 '13 at 14:15
  • Huh, I thought of asking it when writing an answer, but forgot. =) – Yaroslav Mytkalyk Feb 06 '13 at 14:22
  • No, your answer was correct. I was using FragmentPagerAdapter instead of FragmentStatePagerAdapter, and that was the main cause of the problem. Turns out I additionally made the problem worse by keeping a reference :) Thanks! – MichelReap Feb 06 '13 at 14:23
  • @MichelReap: You cannot set setOffScreenPageLimit to zero. It defaults to one. – Ε Г И І И О Aug 01 '14 at 15:32
  • @MichelReap: you generally should not keep references to Fragments as they can be destroyed and recreated by the system at any time, making your references invalid and causing memory leaks – wkarl Nov 18 '14 at 11:03
  • @MichelReap May I ask that what do you mean by holding up a reference to the fragments? I might have similar problem. – Alston Sep 09 '19 at 16:53