I am developing an app that uses a kind of local background. The idea is to make this changable. I manage to change the “background” using this code.
Bitmap bMap = BitmapFactory.decodeFile(sharedPreferences.getString("PICTURE", ""));
Drawable d =new BitmapDrawable(bMap);
bac.setBackgroundDrawable(d);
}
The problem is that each time i return to the “background screen” the app crashes because of OutOfMemoryError. Then it shows the new background. I need some sort of code that makes that the app does not crash. I manage to this in a ImageView but not in LinearLayout. For ImageView I use this code:
Bitmap bMap = BitmapFactory.decodeFile(sharedPreferences.getString("PICTURE", ""));
image.setImageBitmap(bMap);
And to avoid it from crashing:
@Override
protected void onPause() {
super.onPause();
unbindDrawables(findViewById(R.id.iv_pic));
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();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindDrawables(findViewById(R.id.iv_pic));
System.gc();
}
How do I do the same for a LinearLayout?
There are a lot of questions asked on SO about the OOM exception and how to deal with it. Please search the forum before posting a question.
Some notes:
Bitmapusing therecyclemethod (in your code, you can callbMap.recycle())LinearLayoutusingfindViewByIdand pass that to theunbindDrawableslikeunbindDrawables(findViewById(R.id.myLinearLayoutId));