Maduranga E
Maduranga E

Reputation: 1689

How to use CountDownTimer in android?

Following is the program I wrote to use count down timer but when the program is launched in the emulator i get an error message saying "Sorry The application AndroidTestTimer (process android.test.timer) has stopped unexpectedly. Please try again" with the force close button.

Following is the code.

package android.test.timer;

import android.os.CountDownTimer;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidTestTimerActivity extends Activity {
    /** Called when the activity is first created. */
    TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
        TextView tv = (TextView)findViewById(R.id.time_textview);
        tv.setText("Default!");
        MyTimer tim = new MyTimer(6000,1000);
        tim.start();
    }

    public class MyTimer extends CountDownTimer {
        public MyTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
            tv.setText("changed by the constructor");
        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub
            tv.setText("changed by the onFinish");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            tv.setText("time: " + millisUntilFinished);
        }

    }
}

Upvotes: 0

Views: 4862

Answers (1)

Sergey Glotov
Sergey Glotov

Reputation: 20346

You redeclared tv variable in onCreate(), so tv in the Activity is not initialized.
Right code:

tv = (TextView) findViewById(R.id.time_textview);

P.S. Add logcat output in question the next time. "Sorry The application has stopped unexpectedly" says nothing about error.

Upvotes: 3

Related Questions