This snippet here is in my MainActivity.java which calls the "newdrawing()" method of my class named tools.java.
public void onClick(View v) {
String color = null;
switch (v.getId()){
case R.id.newdraw_a:
tools buttons = new tools(this);
buttons.newdrawing();
break;
The "newdrawing()" method is a dialog which asks the user to add another drawing or cancel. When the user clicks "Accept", I want to call a method from another class named "canvas_class.java".
public class tools extends View{
public canvas_class drawing;
public tools(Context context) {
super(context);
}
public void newdrawing(){
final AlertDialog.Builder newDialog = new AlertDialog.Builder(this.getContext());
newDialog.setTitle("New Drawing?");
newDialog.setMessage("You will overwrite all your current drawings. Are you sure you want to add another drawing?");
newDialog.setPositiveButton("Accept", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.dismiss();
drawing.newdrawing();
}
});
newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
newDialog.show();
}
}
Now, I want to ask what is wrong with my code in tools.java that it force closes when I click Accept. Thank you.
My canvas_class looks like this
public class canvas_class extends View {
private Canvas drawCanvas;
public canvas_class(Context context, AttributeSet attrs) {
super(context, attrs);
setupDrawing();
}
public void newdrawing(){
drawCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
invalidate();
}
You are most probably getting a NullPointerException as
drawing is null so it throws a exception, please initialize the
canvas_class drawing variable so that it doesnt throw a exception
I don't know if 'this.attrs' is legal, perhaps someone else could help you, but your constructor for the 'tools' class could be something like this:
public tools(Context context) {
super(context);
drawing = new canvas_class(context, this.attrs);
}
And is better to name classes with uppercase:
class Tools
class CanvasClass
I hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.