Android java.lang.OutOfMemoryError?

Replace:

img.setBackgroundResource(R.drawable.dog_animation);

By:

img.setImageBitmap(decodeSampleBitmapFromResource(R.drawable.dog_animation, width, height));
//dont forget to replace width and heigh by your imageview dimension

An add:

public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {

    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
}

and

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

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

    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

This is from: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html


try stopping your animation at onPause(). there is a big chance its not getting GCED because of that. also optimize ur bitmaps using this site http://tinypng.org, if you don't need the alpha layer, set it to 24bit


In your AndroidManifest.xml keep this inside application tag, add largeHeap like this:

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"/>

In the above answer there is a getResources() missing in

img.setImageBitmap(decodeSampleBitmapFromResource(R.drawable.dog_animation, width, height));

so it becomes

img.setImageBitmap(decodeSampleBitmapFromResource(getResources(), R.drawable.dog_animation, width, height));