title: How to stop a running method before it finish in Android Studio
body: <p>Hello i am new in android, i have a problem when i develop my application.</p>
  
  <p>I have a modal with timer and close button. When the timer is over , the modal will close, or close the modal before the timer is over with close button. Here the picture : 
  <a href="https://i.stack.imgur.com/iJKK1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iJKK1.jpg" alt="enter image description here"></a></p>
  
  <p>But the problem when i close the modal manually with press the close button, the method that run timer is still running and tried to close the modal although the modal is already closed , this is caused my application crashed. The error is </p>
  
  <blockquote>
    <p>java.lang.NullPointerException: Attempt to invoke virtual method
    'java.lang.String android.content.Context.getPackageName()' on a null
    object reference</p>
  </blockquote>
  
  <p>How can i stop the method when i press close button?</p>
  
  <p>Here my timer method to close modal when the timer is over :</p>
  
  <pre><code>public void startTimer(){
          int hoursToGo = 0;
          int minutesToGo = 0;
          int secondsToGo = 10;
  
      int millisToGo = secondsToGo*1000+minutesToGo*1000*60+hoursToGo*1000*60*60;
  
      new CountDownTimer(millisToGo,1000) {
  
          @Override
          public void onTick(long millis) {
              int seconds = (int) (millis / 1000) % 60 ;
              int minutes = (int) ((millis / (1000*60)) % 60);
              String text = String.format("%02d:%02d",minutes,seconds);
              tv.setText(text);
          }
  
          @Override
          public void onFinish() {
              tv.setText("Request Timeout");
          }
      }.start();
  
      final AlertDialog d = (AlertDialog) getDialog();
      final Timer timer2 = new Timer();
      timer2.schedule(new TimerTask() {
          public void run() {
              d.dismiss();
              timer2.cancel(); //this will cancel the timer of the system
  
              Intent i =  new Intent(getActivity(), PromoActivity.class);
              i.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
              getActivity().startActivityForResult(i,0);
          }
      }, 10000);
  }
  </code></pre>
  
  <p>i execute the method in here :</p>
  
  <pre><code>public void onResume(){
      super.onResume();
  
      startTimer();
  }
  </code></pre>