Search code examples
javaandroidontouchlistenertouch-eventontouch

Cannot make a static reference error


So i will just post the code that is giving the error if anyone has any idea as to why this doesn't work let me know, with an explanation. (do not just say that this is a bad way to code or something) (or at least if you do explain yourself). So the code below is supposed to switch to another screen when a color that someone has clicked is true!

public boolean onTouch(View v, MotionEvent event) {
   int x = (int) event.getX();
   int y = (int) event.getY();
   if(isInsideCircle(x, y) ==  true){
      //Do your things here
       if(redColor == lastColor){
// error is here   Intent i = new Intent(this, YouFailed.class);
// and here        Activity.startActivity(i);
       } else {
           addPoints++;
       }
   }else {

   }
   return true;
}

There are two errors:

The constructor Intent(DrawingView, Class<YouFailed>) is undefined

and

Cannot make a static reference to the non-static method startActivity(Intent) from the type Activity


Solution

  • Use v for accessing startActivity method instead of trying to call non-static method in static way:

    Intent i = new Intent(v.getContext(), YouFailed.class);
    v.getContext().startActivity(i);