Android: BitmapFactory.decodeResource returning null

Kevin picture Kevin · Sep 21, 2011 · Viewed 26k times · Source

I can't seem to figure this out. I have 2 java classes with different characteristics, each calling BitmapFactory.decodeResource to get the same image resource, one returns the bitmap while the other returns null. Both classes are in the same package.

Here is the class that works, it calls BitmapFactory.decodeResource which returns the bitmap. I've only included relevant code.

package advoworks.test;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MainScreen extends SurfaceView implements SurfaceHolder.Callback {

    private static final String TAG = MainScreen.class.getSimpleName();

    public MainScreen(Context context) {
        super(context);

        Bitmap bitmap;
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.droid_1);

        //adding the callback (this) to the surface holder to intercept events;
        getHolder().addCallback(this);

        // make the GamePanel focusable so it can handle events
        setFocusable(true);

    }
}

Here is the class that doesn't work. BitmapFactory.decodeResource returns a NULL in debug. I've only included code i felt was relevant.

package advoworks.test;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.Log;

public class Segment {

    private int x;
    private int y;
    private Bitmap bitmap;

    public Segment(int x, int y) {
        Log.d(TAG, "Creating Segment");
        try {
            this.bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.droid_1);
        } catch (Exception e) {
            Log.d(TAG,"Error is " + e);
        }   
        this.x = x;
        this.y = y;
        Log.d(TAG, "Created Segment");
    }
}

Any clue anyone?

Answer

Eli picture Eli · Aug 19, 2015

Check the resolution of your image, if its too big, the BitmapFactory.decodeResource will just return null (no exception)