1

I have some problem, here in my code I am trying to draw canvas on frameLayout but I am getting Null Object Reference exception. By the way when I changed Color.BLACK nothing change only show black rectangle and give error. I use android studio 2.1 and genymotion android emulator 6.0 Marshmallow

Error is like that :

Fatal Exception:main
Process:com.example.myApp
java.lang.NullPointerException : Attempt to invoke virtual method "void android.graphics.Canvas.rawColor(int)" on a null object reference

public class MyCanvas extends SurfaceView implements SurfaceHolder.Callback{

    private boolean mRun= false;
    private final SurfaceHolder mSurfaceHolder;
    private final Object mRunLock = new Object();

    public MyCanvas(Context context, AttributeSet attrs){

        super(context,attrs);
        this.setWillNotDraw(false);
        mSurfaceHolder = getHolder();
        mSurfaceHolder.AddCallback(this);   
    }

    public synchronized void run(){

        if(mRun){

            Canvas c = null;
            try{

                c = mSurfaceHolder.lockCanvas();
                synchronized (mSurfaceHolder){
                    synchronized(mRunLock){
                        if(mRun) doDraw(c);
                    }

                }

            }finally
                if(c != null)
                { mSurfaceHolder.unlockCanvasandPost(c);    }

        }   


    }


    private void onDraw(Canvas canvas){
       canvas.drawColor(Color.YELLOW);
    }
}

my activity layout code is here.

<view class="com.example.myapp.MyCanvas"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:lid="@+id/mycanvas"
/>

my activity class is here

MyCanvas myCanvas = (MyCanvas)findViewById(R.id.mycanvas);
myCanvas.run();
Amit Vaghela
  • 22,772
  • 22
  • 86
  • 142

1 Answers1

1

The problem is that the canvas returned from lockCanvas is null.

Quoting the docs:

The returned Canvas can be used to draw into the surface's bitmap. A null is returned if the surface has not been created or otherwise cannot be edited. You will usually need to implement Callback.surfaceCreated to find out when the Surface is available for use.

So you must implement Callback.surfaceCreated and start editing your canvas after surfaceCreated is being invoked.

Mina Wissa
  • 10,923
  • 13
  • 90
  • 158