Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top