klaasa klaasa - 1 year ago 75
Java Question

Android Studio app crashes on button click

Recently I fixed an error, but now I'm stuck at clearing the canvas for my draw project. I already took a look at some other topics with the same question, but it didn't fix my problem.

package org.arkmap.klaas.testdrawing;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class WriteOnScreenActivity extends AppCompatActivity {
Button clear;
TouchEventView myView;
protected void onCreate(Bundle savedInstanceState) {
myView = new TouchEventView(this, null);
clear.setOnClickListener(new View.OnClickListener() {
public void onClick(View vw) {

public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_write_on_screen, menu);
return true;

public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;

return super.onOptionsItemSelected(item);


package org.arkmap.klaas.testdrawing;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.Random;
* Created by Startklaar on 19-1-2016.
public class TouchEventView extends View {
public Paint paint = new Paint();
private Path path = new Path();
public boolean cc = false;

Random rnd = new Random();

public TouchEventView(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
paint.setARGB(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));

protected void onDraw(Canvas canvas) {
if (cc) {
path = new Path();
Paint clearPaint = new Paint();
clearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawRect(0, 0, 0, 0, clearPaint);
cc = false;
canvas.drawPath(path, paint);

public void clearCanvas()
cc = true;

public boolean onTouchEvent(MotionEvent event) {
float xPos = event.getX();
float yPos = event.getY();

switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(xPos, yPos);
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
return false;

return true;


Hope to get some help here!

EDIT: The error has been fixed, the only problem I have is that the button is not functioning.

Answer Source

myView is not being initialized. You should set it:

 myView = (TouchEventView) findViewById(R.id.XXXX);