I've just started coding in Android SDK and this is my first attempt at a Countdown Timer. I've set the timer to start at the press of the button with setOnClickListener(). The timer doesn't start but the app stops working when I click the button. The device displays a message saying the app has stopped working.
I've written a method to format the time into minutes and seconds. And i've set the call in the onTick() method of the CountDownTimer.
I've posted my code below. Please take a look and point me to where the problem is and what to do. Much appreciated.
package com.example.day1;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView Timer;//Textview to display the timer
//This is the method to format the time into minutes and seconds
public String formatTime(long millis)
{
String output="00:00";
long second=millis/1000;
long minute=second/60;
second=second%60;
minute=minute%60;
String sec=String.valueOf(second);
String min=String.valueOf(minute);
output=min+":"+sec;
return output;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.countdown);
Timer=(TextView) findViewById(R.id.text1);
Button button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new CountDownTimer(60000,1000)
{
public void onTick(long millisUntilFinished){
Timer.setText(formatTime(millisUntilFinished));
}
public void onFinish()
{
onStop();
}
}.start();
}
});
}
}
onStop()
directly, callfinish()
. – Snicolas