Nishikino Maki Nishikino Maki - 1 year ago 90
Android Question

How to stop a running method before it finish in Android Studio

Hello i am new in android, i have a problem when i develop my application.

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 :
enter image description here

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

java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String android.content.Context.getPackageName()' on a null
object reference

How can i stop the method when i press close button?

Here my timer method to close modal when the timer is over :

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) {

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);

public void onFinish() {
tv.setText("Request Timeout");

final AlertDialog d = (AlertDialog) getDialog();
final Timer timer2 = new Timer();
timer2.schedule(new TimerTask() {
public void run() {
timer2.cancel(); //this will cancel the timer of the system

Intent i = new Intent(getActivity(), PromoActivity.class);
i.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
}, 10000);

i execute the method in here :

public void onResume(){


Answer Source

You have to call timer2.cancel(); when you press the close button

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download