Search code examples
androidout-of-memoryimageswitcher

Android ImageSwitcher - OutOfMemory when switching images (very small)


I got some OutOfMemory crashes when switching image in ImageSwitcher, it's very rare but it happens sometimes (never to me, otherway I would be able to debug it haha).

I only have 5 images (PNG) and each of them has something between 10-60kb, so to be honest I am quite surprised. Here is code:

frameImages = new int[]{R.drawable.f_0, R.drawable.f_1, R.drawable.f_2, R.drawable.f_3, R.drawable.f_4};

...
public void switchImage() {
    int frame = getFrame();
    int image = frameImages[frame];

    // imageSwitcher.startAnimation(getAnimation());
    if (frame == 0)
        startYAxisRotation(imageSwitcher, 400);

    imageSwitcher.setImageResource(image); //CRASHES HERE
}

Am I doing something wrong?

Stacktrace:

java.lang.OutOfMemoryError: 
  at android.graphics.BitmapFactory.nativeDecodeAsset(BitmapFactory.java:0)
  at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:677)
  at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:507)
  at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:872)
  at android.content.res.Resources.loadDrawable(Resources.java:3022)
  at android.content.res.Resources.getDrawable(Resources.java:1586)
  at android.widget.ImageView.resolveUri(ImageView.java:648)
  at android.widget.ImageView.setImageResource(ImageView.java:377)
  at android.widget.ImageSwitcher.setImageResource(ImageSwitcher.java:41)
  at com.myapp.MainActivity$5.switchImage(MainActivity.java:143)
  at android.os.Handler.handleCallback(Handler.java:733)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:157)
  at android.app.ActivityThread.main(ActivityThread.java:5293)
  at java.lang.reflect.Method.invokeNative(Method.java:0)
  at java.lang.reflect.Method.invoke(Method.java:515)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
  at dalvik.system.NativeStart.main(NativeStart.java:0)

Solution

  • So, solution was to decrease resolution of images (I did manual resizing in photoshop). From 620x1080 to 800x460 and everything works fine.

    Conclusion: Image size it's not that important - image resolution is.

    PS: MatPag should also be teoretically correct, it's practically same what I did - except he is doing that in code, I did it manually in photoshop by myself. But I think doing that manually is better IMHO.