user6345865 user6345865 - 6 months ago 22
Java Question

CountDown Method for Android not Working [Edited]

I am using Android Studio. So this is the full code. I am trying to start the countdown by clicking the startButton. The plan is that the countdown is going down while I can still click the other button. The other button(incrementButton) increments. I got the increment working but the timer is not working when I click the startButton. Is there something wrong I am doing?

EDIT : Would it also be good to ask on how to cancel the background thread?
I tried using cancel(true). Changed the code

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView seconds;
TextView increment;
int count;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seconds = (TextView) findViewById(R.id.seconds);
increment = (TextView) findViewById(R.id.increment);
Button incrementButton = (Button) findViewById(R.id.incrementButton);
Button startButton = (Button) findViewById(R.id.startButton);
Button stopButton= (Button) findViewById(R.id.stopButton);
incrementButton.setOnClickListener(this);
startButton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.incrementButton:
count++;
increment.setText(Integer.toString(count));
break;
case R.id.startButton:
new timerTask();
break;
case R.id.stopButton:
new timerTask().cancel(true);
break;
}
}
private void updateSeconds(final int count) {
runOnUiThread(new Runnable() {
@Override
public void run() {
seconds.setText(Integer.toString(count));
}
});
}
public class timerTask extends AsyncTask<Void, Void, Void> {
private int i;
private int savedSecond;
public timerTask() {
}
@Override
protected Void doInBackground(Void... voids) {
try {
for(i = 10; i > 0; i--){
savedSecond = i;
updateSeconds(savedSecond);
Thread.sleep(1000); //1000 = 1 seconds
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
}

Answer
case R.id.startButton:
        timerTask timerTask  =new timerTask(); // here you created the timer task.
              timerTask.execute() //execute has to be called.
        break;
Comments