I am loading lots of bitmaps in every activity. I was getting lots of “java.lang.OutOfMemoryError" after switching between activities. My app is mostly on potrait orientation.
I tried many solutions and found a relatively better approach in one of the solutions on this website.
First, set the “id” attribute on the parent view of your XML layout:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/RootView" >
Then, in the onDestroy() method of your Activity, call the unbindDrawables() method passing a refence to the parent View and then do a System.gc()
@Override protected void onDestroy() { super.onDestroy(); unbindDrawables(findViewById(R.id.RootView)); System.gc(); } private void unbindDrawables(View view) { if (view.getBackground() != null) { view.getBackground().setCallback(null); } if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { unbindDrawables(((ViewGroup) view).getChildAt(i)); } ((ViewGroup) view).removeAllViews(); } }
But it does not completely remove java.lang.OutOfMemoryError
. Now I randomly get this memory exception. I have read a few posts stating that for completely getting rid of this issue you have to load bitmaps from code and release them in activity onDestroy which in my case is not a practical solution because I am loading lots of bitmaps.
Does someone have any better solution to this problem?