Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAbhishek Patil
3,329 PointsI want to loop this code
I am trying to make a 30s reminder in android studio. This code counts down from 30 to 0 but then stops, I want it to start counting from 30 again. how do I make a loop?
package com.example.a30sreminder;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle; import android.os.CountDownTimer; import android.view.View; import android.widget.Button; import android.widget.TextView;
public class MainActivity extends AppCompatActivity { private TextView countdownText; private Button countdownButton;
private CountDownTimer countDownTimer;
private long timeLeftInMilliseconds = 30000; //30 seconds
private boolean timerRunning;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countdownText = findViewById(R.id.countdown_text);
countdownButton = findViewById(R.id.countdown_button);
countdownButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startStop();
}
});
updateTimer();
}
public void startStop () {
if (timerRunning) {
stopTimer();
} else {
startTimer();
}
}
public void startTimer () {
countDownTimer = new CountDownTimer(timeLeftInMilliseconds, 1000) {
@Override
public void onTick(long l) {
timeLeftInMilliseconds = l;
updateTimer();
}
@Override
public void onFinish() {
}
}.start();
countdownButton.setText("Pause");
timerRunning = true;
}
public void stopTimer () {
countDownTimer.cancel();
countdownButton.setText("Start");
timerRunning = false;
}
public void updateTimer () {
int seconds = (int) timeLeftInMilliseconds / 1000;
String timeLeftText;
timeLeftText = "" + seconds;
countdownText.setText(timeLeftText);
}
}