I wanted to draw an image on canvas using bitmapFactory, but it gave me an error.

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.isRecycled()' on a null object reference
        at android.graphics.BaseCanvas.throwIfCannotDraw(BaseCanvas.java:54)
        at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:226)
        at android.view.RecordingCanvas.drawBitmap(RecordingCanvas.java:78)
        at com.example.canvastest.GameView.onDraw(GameView.java:23)

I tried to change null paint with actual paint object but it was no good.
I also tried using Rect for space but is was also not good.

    private Bitmap bmp;
    public GameView(Context context) {
        super(context);
        bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.BLUE);
        canvas.drawBitmap(bmp, 10, 10, null);
    }

1 Answers

0
user8194042 On Best Solutions

Try to create method init(Context context) like this:

public void init(Context context) {
    this.context = context;
    bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
}

Then:

public GameView(Context context) {
    super(context);
    init(context);
}

public GameView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
}

public GameView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
}

public GameView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    init(context);
}