Java – member variable null after function returns?

member variable null after function returns?… here is a solution to the problem.

member variable null after function returns?

I have a class that extends View. This class has the member variable mCanvas

private Canvas mCanvas;

This variable is created when the View is resized, so the appropriate Canvas size is set:

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    int curW = mBitmap != null ? mBitmap.getWidth() : 0;
    int curH = mBitmap != null ? mBitmap.getHeight() : 0;
    if (curW >= w && curH >= h) {
        return;
    }

if (curW < w) curW = w;
    if (curH < h) curH = h;

Bitmap canvasBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(canvasBitmap);
    if (mBitmap != null) {
        mCanvas.drawBitmap(mBitmap, 0, 0, null);
    }
    mBitmap = canvasBitmap;
}

But in my onDraw function, when I try to get the width/height of the Canvas, I get a null pointer exception. I’m not sure when onSizeChanged is actually called, I’m assuming it’s always called when the View is created, and therefore before onDraw.

But if my onDraw starts with this:

@Override
protected void onDraw(Canvas canvas) {
    if (mBitmap != null) {
        if(mCanvas == null)
        {
            Log.d("testing","mCanvas is null"
        }

When I arrive at onDraw, logCat always displays the message “mCanvas is null”.

So I changed the code and if mCanvas is empty when I read onDraw, I’ll recreate it :

private void resizeCanvas()
{
    int curW = mBitmap != null ? mBitmap.getWidth() : 0;
    int curH = mBitmap != null ? mBitmap.getHeight() : 0;

if (curW >= this.getWidth() && curH >= this.getHeight()) {
        return;
    }

if (curW < this.getWidth()) curW = this.getWidth();
    if (curH < this.getHeight()) curH = this.getHeight();

Bitmap canvasBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(canvasBitmap);

if (mBitmap != null) {
        mCanvas.drawBitmap(mBitmap, 0, 0, null);
    }

mBitmap = canvasBitmap;
}

@Override
protected void onDraw(Canvas canvas) {
    if (mBitmap != null) {
        if(mCanvas == null)
        {
            resizeCanvas();
            if(mCanvas == null)
            {
                Log.d("test","canvas is still null");
            }

logCat still prints “canvas is still null”

Can someone explain what’s going on here? I’m new to Android, and most of the code comes from the TouchPaint example that I’ve been playing with.

If I check if mCanvas is empty inside the resizeCanvas function, it always says it’s not empty. However, if I check immediately after calling the function, it is always null.

Solution

I think the problem is in your resizeCanvas because you can return from mCanvas before initializing it.

Related Problems and Solutions