Why does my TimerTask.cancel() returns an NPE ? (JAVA)
<p>I'm coding an assignment and currently everything's working fine. I'm not going to post the whole thing but the essential classes being called and referenced. </p>

<p>Basically, my problem is that I have a GameTimer class to start a Timer in my Game: </p>

<pre><code>public class GameTimer  {

    GameViewController gvc = GameFrame.gameViewController;
    public static boolean isRunning = false;

    public int seconds = 0;

    public Timer timer = null;
    public TimerTask task = null;

    public GameTimer () {
        timer = new Timer();
    }

    public void start() {
        task = new TimerTask() {
            @Override
            public void run() {
                gvc.updateTime(seconds);
                seconds++;
            }
        };
        timer.scheduleAtFixedRate(task, 1000, 1000);
        System.out.println("Task was started");
        isRunning = true;
    }

    public void stop() {
        task.cancel();
        timer.cancel();
        timer.purge();
        isRunning = false;
    }

    public void restart() {
        stop();
        start();
    }
}
</code></pre>

<p>And basically I have different modes that extends a GameModel and references my GameTimer instance in my GameModel class : </p>

<pre><code>public class GameModel {
    public GameTimer game_timer = new GameTimer();
    //... Rest of instances and classes
}

public class Mode1 extends GameModel {
    public Mode1() {
        if(!gamer_timer.isRunning)
            game_timer.start();
        else
            game_timer.restart();
    }
    //.....Rest of methods
}

public class Mode2 extends GameModel {
    public Mode2() {
        if(!gamer_timer.isRunning)
            game_timer.start();
        else
            game_timer.restart();
    }
    //.....Rest of methods
}
</code></pre>

<p>Basically, my game is a GUI and i have a drop-down box from which I select my modes. My game instantly loads Mode1 when it runs, but when I choose Mode2, it returns a NullPointerException on my </p>

<pre><code>  task.cancel();
</code></pre>

<p>I've read on some other posts that you have to cancel the TimerTask before the Timer, but whether I put timer cancel before the task cancel
       task.cancel<br>
       timer.cancel()
it still gives me the same NullPointerException</p>

<p>Here's the error: </p>

<pre><code>  Exception in thread "AWT-EventQueue-0" Mode2
  java.lang.NullPointerException
       at GameTimer.stop(GameTimer.java:32) // task.cancel()
       at GameTimer.restart(GameTimer.java:39)
       at Mode2.&lt;init&gt;(Mode2.java:15)
</code></pre>

<p>Can you help me just figure out why is the task not cancelling. </p>