This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                                3年前关闭。
            
                    
我有一些问题,在我的代码中,我试图在frameLayout上绘制画布,但是我收到了Null Object Reference异常。顺便说一下,当我更改Color.BLACK时,没有任何变化,仅显示黑色矩形并给出错误。
我使用android studio 2.1和genymotion android emulator 6.0棉花糖

错误是这样的:

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);
    }
}


我的活动布局代码在这里。

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


我的活动课在这里

MyCanvas myCanvas = (MyCanvas)findViewById(R.id.mycanvas);
myCanvas.run();

最佳答案

问题是从lockCanvas返回的画布为空。

引用文档:


  返回的Canvas可用于绘制表面的位图。一种
  如果尚未创建曲面,则返回null
  无法编辑。您通常需要实施
  Callback.surfaceCreated来确定何时可用于Surface
  采用。


因此,您必须实现Callback.surfaceCreated并在调用surfaceCreated之后开始编辑画布。

07-28 02:01