我需要找出surfaceview上drawCircle方法缺少的内容。
在getholder()
中调用onCreate
后调用lockcanvas,并且从方法中尝试了同样的操作,但是我收到了错误。
这里是主要活动:
public class MainActivity extends AppCompatActivity {
private Main2Activity contentView;
Tester tester;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("App", "App launched");
tester = new Tester(this);
// GameView gameView = new GameView(this);
Log.d("App", "set calling.");
setContentView(tester);
}
@Override
protected void onResume() {
super.onResume();
Log.d("App", "onResume");
tester.resume();
}
}
这里绘制圆圈的方法:
public class Tester extends SurfaceView {
Canvas canvas;
Paint paint;
boolean b;
SurfaceHolder surfaceHolder;
public Tester(Context context) {
super(context);
Log.d("App", "in other context.");
// canvas = new Canvas();
// paint = new Paint(Paint.ANTI_ALIAS_FLAG);
// surfaceHolder = getHolder();
// canvas = surfaceHolder.lockCanvas();
// setWillNotDraw(false); //this line is very important!
}
/*
public void run() {
Log.d("App", "in running.");
synchronized (canvas = surfaceHolder.lockCanvas()) {
while (b) {
drawing();
Log.d("App", "drawing passed");
}
}
}
*/
private void drawing() {
Log.d("App", "posting.");
surfaceHolder = getHolder();
canvas = surfaceHolder.lockCanvas();
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
synchronized (canvas = surfaceHolder.lockCanvas()) {
paint.setColor(Color.MAGENTA);
canvas.drawCircle(100, 200, 20, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
void resume() {
b = true;
drawing();
}
}
logcat的:
引起:java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.graphics.Canvas.drawCircle(float,float,float,android.graphics.Paint)'
我找不到可能出错的内容,这个简单的代码片段没有实例化的内容? 谢谢你的时间。
答案 0 :(得分:0)
正如您在评论中提到的那样:
请提及nullPointer异常的原因。我想知道它。 :)
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Canvas.drawCircle(float, float, float, android.graphics.Paint)' on a null object reference
您的LogError
明确表示Canvas
的对象为空,这意味着您在代码中使用的Canvas
实例不存在或为空。
看这里:
here --> canvas.drawCircle(100, 200, 20, paint);
此处Canvas
canvas
的引用为null,请尝试初始化。