0

I have a ViewPager with a couple of fragments. In a fragment onCreateView,

I decode a couple of bitmaps that are assigned to fields in the Fragment class. If I try to swipe between the fragments, at a certain point the application gets an OutOfMemory exception (heap is exhausted).

Ok, this is a really bad practice, but, isn't the GC supposed to free memory before my application is killed?

Reassigning the Bitmap to the same field should cause the previous Bitmap to be released, am I wrong? On S4 I get the exception very soon.

Maz I
  • 3,664
  • 2
  • 23
  • 38

2 Answers2

1

Suppose you load a bitmap, lets say that is the first and then assign a new decoded second bitmap to the first, the first bitmap is not GC'ed when you decode the second one. GC will do it later whenever it decides. If you want to free memory ASAP you should call recycle() just before decoding the second bitmap. Src: here. And, go through Android's Managing Bitmap Memory article. Refer this too.

Community
  • 1
  • 1
Srikanth
  • 2,014
  • 19
  • 22
  • Wouldn't be better to run GC before throwing an OutOfMemory? Is there a reason why it is not done? – user2882491 Feb 05 '14 at 15:36
  • "On Android 2.3.3 (API level 10) and lower, the backing pixel data for a bitmap is stored in native memory. It is separate from the bitmap itself, which is stored in the Dalvik heap. The pixel data in native memory is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash." Calling recycle() frees up the native memory. – Srikanth Feb 06 '14 at 04:22
0

Fragments are kept in memory unless stated otherwise, so either you manually detach and dispose of fragments when swiping or mBitmap.recycle() when swiping.

Edit, code:

     final FragmentTransaction fm = getActivity()
            .getSupportFragmentManager().beginTransaction(); 
    fm.replace(R.id.fragPlayerMain, playerFragment, "fragment").addToBackStack(null);
    fm.hide(thisFrag);
    fm.detach(thisFrag);
    fm.commitAllowingStateLoss();
Pontus Backlund
  • 1,017
  • 1
  • 10
  • 17