0

When I try to set wallpaper from Drawable resource I have received OutOfMemoryError. How can I fix this problem?

Context context = v.getContext();
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
try { 
    Drawable drawable = context.getResources().getDrawable(wpResID);
    Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
    wallpaperManager.setBitmap(bitmap);

    bitmap.recycle();
    bitmap = null;
} catch (IOException e) {
    e.printStackTrace();
}

I have received this:

05-22 16:03:13.001: E/AndroidRuntime(30942): FATAL EXCEPTION: main
05-22 16:03:13.001: E/AndroidRuntime(30942): java.lang.OutOfMemoryError
05-22 16:03:13.001: E/AndroidRuntime(30942):    at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
05-22 16:03:13.001: E/AndroidRuntime(30942):    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:521)
05-22 16:03:13.001: E/AndroidRuntime(30942):    at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:374)
05-22 16:03:13.001: E/AndroidRuntime(30942):    at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:785)
05-22 16:03:13.001: E/AndroidRuntime(30942):    at android.content.res.Resources.loadDrawable(Resources.java:2005)
05-22 16:03:13.001: E/AndroidRuntime(30942):    at android.content.res.Resources.getDrawable(Resources.java:673)
Dmytro Zarezenko
  • 10,526
  • 11
  • 62
  • 104

1 Answers1

0

Use BitmapFactory.Options.inSampleSize when you first load your image to get the size as close as possible to your target size, then use Bitmap.createScaledBitmap to scale to the exact size you want.

There's some code for this in this answer.

Community
  • 1
  • 1
Erzer
  • 86
  • 3
  • As I see I receive this error in this line `Drawable drawable = context.getResources().getDrawable(wpResID)` and I store needed sizes of images so no resize needed. – Dmytro Zarezenko May 22 '14 at 13:41
  • Try android:largeHeap="true" to increase heap size for your app in your menifest – Erzer May 22 '14 at 13:55
  • And you can try to find memory leak. How to this here - http://android-developers.blogspot.ru/2009/02/track-memory-allocations.html – Erzer May 22 '14 at 13:58