So I am just trying to create a simple draw view where a user can draw on the screen. However after hours of research I still seem to be having trouble solving why, when I call canvas.drawPath() in my onDraw() method, the app crashes. (I have omitted touch methods here)
public class DrawTing extends View{
private Bitmap bm;
private Canvas canv;
private Path path;
Context context;
private Paint paint1;
private Paint paint;
public DrawTing(Context c) {
super(c);
this.context = c;
}
public DrawTing(Context c, AttributeSet attrs) {
super(c, attrs);
this.context = c;
}
public DrawTing(Context c, AttributeSet attrs, int defStyle) {
super(c, attrs, defStyle);
this.context = c;
path = new Path();
paint = new Paint();
paint.setDither(true);
paint.setAntiAlias(true);
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(10f);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
canv = new Canvas(bm);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(path, paint); //NPE here
//Things I have tried along with canvas.drawPath()
//canvas = this.canv
//canvas = canv;
//canvas = new Canvas();
//canvas.drawRect(0,0, getWidth(), getHeight(), paint);
//canvas.drawColor(0xFFAAAAAA);
//canvas.drawBitmap(bm,0,0, paint);
}
My logcat is displaying this error message:
FATAL EXCEPTION: main
Process:
com.ting.cian.ting, PID: 7989
java.lang.NullPointerException: Attempt to read from field 'boolean
android.graphics.Path.isSimplePath' on a null object reference
at
android.graphics.BaseCanvas.drawPath(BaseCanvas.java:295)
at
android.graphics.Canvas.drawPath(Canvas.java:1652)
at
com.ting.cian.ting.DrawTing.onDraw(DrawTing.java:124)
at
android.view.View.draw(View.java:19119)
at
android.view.View.updateDisplayListIfDirty(View.java:18069)
at
android.view.View.draw(View.java:18847)
at
android.view.ViewGroup.drawChild(ViewGroup.java:4214)
at
android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
at
android.view.View.updateDisplayListIfDirty(View.java:18060)
at
android.view.View.draw(View.java:18847)
...
Thanks for your time!