Seekbar sync with timer - java

I am new at programming in Android and I am trying to figure out how to link the seekbar with my timer. In my program I allow the user to put in a time then click start timer, which then sends that value to a TextView and decrements seconds until finished. I would like the seekbar to "follow" along. Any help would be appreciated!
I've got the seekbar to sort of follow the timer but now its too choppy... is there an easy way to make a smooth progress?
public void startTimer() {
int min = Integer.parseInt(edit_minute.getText().toString());
int sec = Integer.parseInt(edit_second.getText().toString());
int value = (min * 60) + sec;
seek_bar.setMax(value *10000);
new CountDownTimer(getValues(), 1000) { // adjust the milli seconds here
public void onTick(long millisUntilFinished) {
text1.setText(""
+ String.format(
FORMAT,
TimeUnit.MILLISECONDS
.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS
.toMinutes(millisUntilFinished)
- TimeUnit.HOURS
.toMinutes(TimeUnit.MILLISECONDS
.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS
.toSeconds(millisUntilFinished)
- TimeUnit.MINUTES
.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millisUntilFinished))));
seek_bar.setProgress((seek_bar.getProgress() + 1));
}
public void onFinish() {
text1.setText("done!");
}
}.start();

You just need to update it from your CountDownTimer. First, create an instance variable:
SeekBar progressBar;
Within your onCreate, get a reference to the seek bar:
progressBar = (SeekBar) findViewById(R.id.seek_bar_current);
Once you start the timer, tell progressBar the maximum it should go to:
progressBar.setMax(); // How ever long the timer will run for
Then in the CountDownTimer, update the progress:
progressBar.setProgress(); // The total time, minus millisUntilFinished

Related

How to show image for 30 seconds then show another one after 30 seconds for multiple images?

I only managed to change between 2 images but I would like to change more than 2 images. I am creating a fitness application where each exercise is 30 seconds long, after 30 seconds, the next exercise starts. Each workout has about 5 exercises but I am only able to change between 2 images. Currently, after the timer hits 30 seconds, it will change to the next image but the timer stops there. I heard that I need to use array and loop but I am not sure how to... Can somebody help me? Your help will be greatly appreciated as my submission is due in 5 days ><
private void startTimer(){
countDownTimer = new CountDownTimer(30000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDowntText();
}
#Override
public void onFinish() {
exercise_image.setImageResource(R.drawable.lunges);
exercise_name.setText("Alternate Lunges");
}
}.start();
mTimerRunning = true;
}
private void updateCountDowntText(){
int seconds = (int) (mTimeLeftInMillis / 1000) % 30;
String timeLeft = String.format(Locale.getDefault(), "%02d", seconds);
timerValue.setText(timeLeft);
}
if your images are in R.drawables. then simply store the int reference in your array and then load that such as below,
private int[] yourarray = {
R.drawable.star_00, //star_00 is image name here
R.drawable.star_01,
R.drawable.star_02,
};
Then when you want to load an image and draw to your imageview you do something like this from your Activity.
Drawable d = getResources().getDrawable(yourarray[n]);
Then call the setImageDrawable on ImageView. So:
yourImageView.setImageDrawable(d);

ValueAnimator in Android and how to make it increase by one each second

I'm working on this android app...and I have a textview, where I'd like to count UP. In this textview I have the statement "This page was refreshed X seconds ago". Every 20 seconds I'd like it to restart its countup from 0.
I've implemented a function which uses the ValueAnimator class. However, I'm not sure how to make the ValueAnimator increase the integer value by 1 every second. I'd like it to count up like a clock's second hand 1...2..3...4..5......20. Right now its counting up incredibly fast...and I want to slow it waaayyyy down. 1 count per second.
Please how do I do this? I've looked at some of the method calls for ValueAnimator, and I'm not sure how to slow it down...right now it's so fast.
Also, where would I add a method call, lets say, everytime the counter gets to 20 seconds? Lets say I want to call refreshView() when it gets to 20, before it starts all over.
Thank you for your time, and thanks for your help.
The ValueAnimator class:
https://developer.android.com/reference/android/animation/ValueAnimator
In my method I have:
ValueAnimator valueAnimator = ValueAnimator.ofInt(initialValue, finalValue);
valueAnimator.setDuration(10000);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
textview.setText("This page was refreshed " + valueAnimator.getAnimatedValue().toString() + " seconds ago");
}
});
valueAnimator.start();
// Repeat 100 times
valueAnimator.setRepeatCount(100);
ValueAniamtor is used for animation. Animation are refreshed at very high rate. I don't think that you can count seconds with a valueAnimator.
In one of my apps i use a Timer to refresh periodically a textView.
final TextView textview=findViewById(R.id.tv);
new Timer().scheduleAtFixedRate(new TimerTask() {
int value=0; //start at 0
#Override
public void run() {
value++ ;
runOnUiThread(new Runnable() { //only the main thread can touch his views
#Override
public void run() {
textview.setText("This page was refreshed " + value + " seconds ago"); //refresh text
}
});
}
}, 0, 1000); //reschedule every 1000 milliseconds
}

[eclipse]I want to add another move for my button in the timer [duplicate]

This question already has an answer here:
my timer in eclipse did not work properly
(1 answer)
Closed 8 years ago.
guys I am new to the eclipse, I am practicing the timer in eclipse, can I have some help for my codes?
The code below is like if I clicked the trigger button while it is counting, it will trigger another counting without stop the previous counting.
I have tried chancel the button or reactive it after the down counting, still i want to know how to make the same trigger button acquire the restart counting function. Can u help me by directly embed to my code please? I know i am too new to eclipse, java even eng, everything, i would need your explanation if it is not going to take your take too much.
Button countDownButton2 = (Button) findViewById(R.id.countDown1);
countDownButton2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
CountDownTimer timer2 = new CountDownTimer(3000,1000){
#Override
public void onFinish() {
mTimeLabel1.setText("Times Up baby!");
}
#Override
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
mTimeLabel1.setText("" + minutes + ":"
+ String.format("%02d", seconds));
}
}.start();
}
});
Your current solution is creating an new countdowntimer but not stopping the old one. Therefore if you click the button again you have 2 countdown timers. When you say "new CountDowntimer", that is when you create it. Therefore, before you create a new one, make sure to stop the previous one.
Button countDownButton2 = (Button) findViewById(R.id.countDown1);
countDownButton2.setOnClickListener(new View.OnClickListener() {
CountDownTimer timer2;
public void onClick(View view){
if(timer2!=null){
timer2.cancel();
}
timer2 = new CountDownTimer(3000,1000){
#Override
public void onFinish() {
mTimeLabel1.setText("Times Up baby!");
}
#Override
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
mTimeLabel1.setText("" + minutes + ":"
+ String.format("%02d", seconds));
}
}.start();
}
});
Explanation
Previously, each time you clicked the button you had a new CountDownTimer. Each countdown timer was changing the value of the label mTimeLabel1. The new timer is created because inside your on click lister, you were doing this:
CountdownTimer2 timer2 = new CountDownTimer(3000,1000)
This means, create a new Timer, and keep a reference to it called timer2. After the onClick method is finished, the timer keeps running. However, when you click again you create a new timer and a new reference to the old timer is lost. The reference is not to the old one but to the new one.
So, instead we make sure that the click listener has only one timer. To do this we move the reference to it outside of the onClick method so that we can keep the reference to the timer. We can then make sure that we check this timer to cancel it before starting another one. However, if it is the first time that you have clicked on the button then the timer will be null, because "new CountdownTimer" hasn't yet been called. So, we check that it is not null (it's not the first button press), and if it is not then cancel the old one before creating a new one. If it is the first button press, we don't want to call cancel because there is no timer to cancel.

CountDownTimer continues to tick in background — How do I retrieve that count in onResume?

I have an app with multiple timers; when I start one, I can see it counting down in Logcat in Eclipse.
When I hit the Back button, onStop() is called in the app but the timer continues to countdown in logcat (the onTick() is continuing to tick away).
What I would like is when onResume() is called, I want to get that timer which is still counting down and continue it. Is this possible?
Here are my buttons that start the countdown:
//Button1 Timer
final CountDown button1 = new CountDown(420000,1000,bButton1);
bButton1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
button1.start();
long currentTime = System.currentTimeMillis();
//Set start time for calculating time elapsed if needed
saveTime("START_TIME_BUTTON1", currentTime);
}
});
//Button2 Timer
final CountDown button2 = new CountDown(360000,1000,bButton2);
bButton2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
button2.start();
long currentTime = System.currentTimeMillis();
//Set start time for calculating time elapsed if needed
saveTime("START_TIME", currentTime);
}
});
My onResume() looks like this:
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//Reset the timers on appropriate buttons if there was something running
//If nothing was running or timer finished - have button in default state
//See if there was a button1 timer running - if not, it will be 0
SharedPreferences start = PreferenceManager.getDefaultSharedPreferences(this);
long startTime = start.getLong("START_TIME_BUTTON1", 0);
long timeElapsed = (System.currentTimeMillis()-startTime);
long timeRemaining = (420000 - timeElapsed);
if (timeRemaining == 0) {
} else if (timeRemaining > 0) {
final CountDown button1Timer = new CountDown(timeRemaining,1000,bButton1);
button1Timer.start();
long currentTime = System.currentTimeMillis();
saveTime("START_TIME", currentTime);
} else {
}
}
This actually works — the onResume() starts another timer right where the first one would be, and the text displays the appropriate number and continues counting down with the onTick() method. But now logcat shows 2 timers counting down instead of just one!
Ultimately I wouldn't want to start another timer, I just want to pick up the first timer I started where it is currently in the countdown at and have the onTick() display appropriately. Is there a way to do that? Would services be what I'm looking for? Is it already a service since it continues to tick down in the background?
I'm a little confused on what would be best practice to get this done.
onTick() will continue being called until either the time remaining reaches 0 or you call cancel() on the CountDownTimer.
So in your onStop() method you will need to call cancel() on the timer you want to stop receiving onTick() notifications.
Android's implementation of CountDownTimer uses a Handler to perform timing by queuing a Message to be sent to the Handler after each tick. Unfortunately there is no way to pause the CountDownTimer, so I believe you will need to create a new Timer with the appropriate values like you're doing currently.
When you're calculating the timeElapsed, you shouldn't use System.currentTimeMillis() because it can be changed at any time, instead you should use SystemClock.elapsedRealtime(). System.currentTimeMillis() is the timer used for the wall clock (time and date) and so can change unpredictably, see the Android documentation.

Timer Stops working when screen turn off

Hi im a newbie in Android & java lang.
i have this code that tells you how long have you been playing.
the code works fine, except when the screen turns off or when the user press the power button (sleep mode) it stop working.
can any one suggest a simple code to keep my time counting even when the screen is off or in sleep mode. Thanks...
public class test extends Activity
{
Handler mHandler = new Handler();
Runnable mUpdateTime = new Runnable()
{
public void run()
{
sec += 1;
if(sec >= 60)
{
sec = 0;
min += 1;
if (min >= 60)
{
min = 0;
hour += 1;
}
}
playtime.setText(String.format("%02d:%02d:%02d", hour, min, sec));
mHandler.postDelayed(mUpdateTime, 1000);
}
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mHandler.postDelayed(mUpdateTime, 1000);
}
}
I would suggest not counting the time, rather setting a start time and then subtracting that from the current to get the elapsed time.
A Chronometer widget might solve your problems.
I would advise against any solution where you might have to count during sleep mode, since that will kill the user's battery life.

Categories

Resources