Question

I'm re-writing an Android app where each activity (there are several) displays a background image. The user may change this image and so I've done the following:

  1. Created MyAppApplication (extends Application), a reference to which is set up in onCreate() in each activity.
  2. MyAppApplication has a public BitmapDrawable which is applied to the background on start.
  3. Each activity listens for changes in SharedPreferences and re-loads the background image on such changes.

Here's part of the code I used to set the image, based on http://developer.android.com/training/displaying-bitmaps/load-bitmap.html:

Bitmap bitmap = decodeBitmap(R.drawable.background_image, screen_width, screen_height);
}
public BitmapDrawable backgroundImage = new BitmapDrawable(bitmap);

public Bitmap decodeBitmap(int resId, int reqWidth, int reqHeight)
{
  // First decode with inJustDecodeBounds=true to check dimensions
  final BitmapFactory.Options options = new BitmapFactory.Options();
  options.inJustDecodeBounds = true;
  BitmapFactory.decodeResource(getResources(), resId, options);

  // Calculate inSampleSize
  options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

  // Decode bitmap with inSampleSize set
  options.inJustDecodeBounds = false;
  return BitmapFactory.decodeResource(getResources(), resId, options); // crashes here
}

Then, in the activity, I set the background to backgroundImage.

The first time the app starts up this works, but if the shared preferences are changed then the application tries to decode the resource again and the app crashes at the point marked above. May I ask what I might do to avoid this?

Was it helpful?

Solution

every time you are done using a Bitmap, you should release them, since they take up a lot of memory.

in onDestroy() you should write something like:

bitmap.recycle();
bitmap = null;

you should also call these lines whenever you stop using the bitmap.

OTHER TIPS

I'll accept the original answer as it is indeed correct that setting the bitmap to null is what is required. The problem was that I was setting it in the wrong place.

The error occurs in the application when the bitmap is read, but it is because of a bitmap in the activity. So, I had to do this in each activity to fix it:

layout.setBackgroundDrawable(null);
layout.setBackgroundDrawable(myApplication.getBackground());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top