I wrote a timer code. the clear function doesn't clear the time value (when I press clear only the text changes, but the time value continues form stop point) here is the code, any suggestions to activate the clear button?:
public class MainActivity extends Activity {
private Button startButton;
private Button stopButton;
private Button clearButton;
private TextView timeValue;
private long timeStart = 0L;
private Handler timeHandler = new Handler();
long timeInMilisec = 0L;
long timeMemo = 0L;
long timeUpdate = 0L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timeValue = (TextView) findViewById(R.id.timeValue);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeStart = SystemClock.uptimeMillis();
timeHandler.postDelayed(updateTimerThread, 0);
}
});
stopButton = (Button) findViewById(R.id.stopButton);
stopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeMemo += timeInMilisec;
timeHandler.removeCallbacks(updateTimerThread);
}
});
clearButton = (Button) findViewById(R.id.clearButton);
clearButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.clearButton:
timeValue.setText("00:00:00");
int secs = 0;
int mins = 0;
secs = 0;
int milliseconds = 0;
timeInMilisec = SystemClock.uptimeMillis() - timeStart;
timeUpdate = timeMemo + timeInMilisec;
timeValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
timeHandler.removeCallbacksAndMessages(updateTimerThread);
timeValue.setText("00:00:00");
break;
}
}
});
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilisec = SystemClock.uptimeMillis() - timeStart;
timeUpdate = timeMemo + timeInMilisec;
int secs = (int) (timeUpdate / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (timeUpdate % 1000);
timeValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
timeHandler.postDelayed(this, 0);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
You should reset the timeMemo variable.
clearButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.clearButton:
// Clear the timestart and timeMemo
timeMemo = 0L;
timeValue.setText("00:00:00");
int secs = 0;
int mins = 0;
secs = 0;
int milliseconds = 0;
timeInMilisec = SystemClock.uptimeMillis() - timeStart;
timeUpdate = timeMemo + timeInMilisec;
timeValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
timeHandler.removeCallbacksAndMessages(updateTimerThread);
timeValue.setText("00:00:00");
timeHandler.removeCallbacks(updateTimerThread);
break;
}
}
});
In the ClearButton onClick you are not reseting the value of the "timerstart" and "timeMemo" variables. That is why only the text is being updated but the timer is not being reset.
Related
public class MainActivity extends AppCompatActivity {
int foulCounterA = 0;
int scoreOnePointTeamA = 0;
int periodCount = 0;
private TextView tv1;
private TextView period;
private Button startbtn, cancelbtn;
private ToggleButton togbtn;
private boolean isPaused = false;
private boolean isCanceled = false;
private long remainingTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
period = (TextView) findViewById(R.id.period_number);
startbtn = (Button) findViewById(R.id.startBtn);
cancelbtn = (Button) findViewById(R.id.cancelBtn);
togbtn = (ToggleButton) findViewById(R.id.togBtn);
cancelbtn.setEnabled(false);
togbtn.setEnabled(false);
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
foulCounterA = 0;
foulCounterB = 0;
displayForTeamAFoul(foulCounterA);
displayForTeamBFoul(foulCounterB);
if (periodCount < 3)
periodCount = periodCount + 1;
else periodCount = 4;
period.setText("Period " + periodCount);
startbtn.setEnabled(false);
cancelbtn.setEnabled(true);
togbtn.setEnabled(true);
isPaused = false;
isCanceled = false;
long millisInFuture = 20000; /////20sec
long countDownInterval = 1000; /////1sec
new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
if (isPaused || isCanceled) {
cancel();
} else {
tv1.setText("" + millisUntilFinished / 1000);
remainingTime = millisUntilFinished;
}
}
#Override
public void onFinish() {
startbtn.setEnabled(true);
togbtn.setEnabled(false);
if (periodCount < 4)
tv1.setText("Times up!");
else tv1.setText("Game Over!");
}
}.start();
}
});
togbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (togbtn.isChecked()) {
isPaused = true;
} else {
isPaused = false;
long millisInFuture = remainingTime;
long countDownInterval = 1000; /////1sec
new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
if (isPaused || isCanceled) {
cancel();
} else {
tv1.setText("" + millisUntilFinished / 1000);
remainingTime = millisUntilFinished;
}
}
#Override
public void onFinish() {
startbtn.setEnabled(true);
togbtn.setEnabled(false);
if (periodCount < 4)
tv1.setText("Times up!");
else tv1.setText("Game Over!");
}
}.start();
}
}
});
cancelbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isCanceled = true;
period.setText("Period");
tv1.setText("Timer");
startbtn.setEnabled(true);
togbtn.setEnabled(false);
cancelbtn.setEnabled(false);
foulCounterA = 0;
foulCounterB = 0;
periodCount = 0;
displayForTeamAFoul(foulCounterA);
displayForTeamBFoul(foulCounterB);
}
});
}
public void onePointForTeamA(View v) {
scoreTeamA = scoreTeamA + 1;
scoreOnePointTeamA = scoreOnePointTeamA + 1;
displayForTeamA(scoreTeamA);
displayForTeamAOnePoint(scoreOnePointTeamA);
}
public void foulCountForTeamA(View v) {
if (foulCounterA < 5)
foulCounterA = foulCounterA + 1;
else
foulCounterA = 5;
displayForTeamAFoul(foulCounterA);
}
public void displayForTeamAOnePoint(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_score_1_point);
scoreView.setText(String.valueOf(score));
}
public void displayForTeamAFoul(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_foul);
scoreView.setText(String.valueOf(score));
}
}
I wanted to make the java code as simple as I can so I've just added the lines for my question. What I'm trying to do is
android:onClick="onePointForTeamA"make this button only clickable when foulCounterA = 5 Failed to add if (foulCounterA = 5); inside public void foulCountForTeamA(View v) {
It gave me an error that way. Says required: boolean, found: int.
What should I do with the code? Any help will be appreeciated
Regarding your concrete question, the syntax of if (foulCounterA = 5); is wrong, because the equation check is have to made by == operator.
So the correct syntax would be if (foulCounterA == 5);
As #OH GOD SPIDERS wrote in the comment, you should check the basics of java operators.
Also I recommend You to search for the answer before asking a new question.
Hello im working with an jumpingApp that will count how many times you are jumping and im using accelorometer sensor.
The problem i got is that i don't really know how to put the delay so it is perfect, sometimes a jump counts as 2 jump sometimes it doesn't register and sometimes it works good. I would like to have around 0.4sec on every count jump.
private TextView textView;
private TextView text;
private SensorManager sensorManager;
double ax,ay,az;
boolean newJumpAccepted = true;
int numbersOfJumps = 0;
long startTime = 0;
int count;
MediaPlayer mediaPlayer;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
if(millis>400){
newJumpAccepted = true;
} else {
newJumpAccepted = false;
}
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerHandler.postDelayed(this,500);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
text = (TextView) findViewById(R.id.text);
textView = (TextView) findViewById(R.id.textView);
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
#Override
public void onSensorChanged(SensorEvent event){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String result = "";
double d = Math.round(event.values[1]);
float threshold = preferences.getFloat("hello", 11);
if (d != 0 && d >= threshold && newJumpAccepted){
count++;
}
Log.i("hej", String.valueOf(d));
text.setText("Jump made" + " " + count + " " + d);
text.invalidate();
startTime();
}
private void startTime() {
if(newJumpAccepted) {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
}
newJumpAccepted = false;
}
}
Timer timer;
MyTimerTask myTimerTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
text = (TextView) findViewById(R.id.text);
textView = (TextView) findViewById(R.id.textView);
if(timer != null){
timer.cancel();
}
timer = new Timer();
myTimerTask = new MyTimerTask();
timer.schedule(myTimerTask, 400, 400);
}
class MyTimerTask extends TimerTask {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!newJumpAccepted) {
text.setText(String.valueOf(count));
newJumpAccepted = true;
}
}
});
}
}
I want to make a Timer Application which plays an alarm after a specific time has elapsed. I am new to Android Development so i picked up an example timer code from the Internet and am trying to modify it to my needs.
I have completed part where the timer plays the alarm when 1 minute has elapsed, but the alarm sound does not stop how can i do that.
My code is given below:
package com.example.aditya.timerapp;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
private ProgressBar progress;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
int progressStatus = 0;
private boolean stopped = false;
#Override
public void onCreate(Bundle savedInstanceState) {
//final CountDown timer = new CountDown();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerValue = (TextView) findViewById(R.id.timerVal);
Button startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//timer.start();
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
});
Button pauseButton = (Button) findViewById(R.id.stopButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
/*try {
timer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}*/
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});
Button resetButton = (Button) findViewById(R.id.resetButton);
resetButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//timeSwapBuff += timeInMilliseconds;
timeInMilliseconds = 0L;
timeSwapBuff = 0L;
updatedTime = 0L;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
customHandler.removeCallbacks(updateTimerThread);
onStop();
}
});
progress = (ProgressBar) findViewById(R.id.progressBar);
}
/*public void stopRun() {
//if (updatedTime == 0) {
//Toast.makeText(new MainActivity(), "StopRun",Toast.LENGTH_LONG).show();
timeSwapBuff = 0;
timerValue.setText("00:00:000");
//updateTimerThread.
customHandler.removeCallbacks(updateTimerThread);
//}
}*/
private Runnable updateTimerThread = new Runnable() {
#Override
public void run() {
//long totalMilliseconds = 1500000;
//while (!stopped){
//long totalMilliseconds = 15000;
//updatedTime = totalMilliseconds - SystemClock.currentThreadTimeMillis();
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
if (mins == 1 && secs == 0) {
playTimer();
}
}
};
public ProgressBar getProgress() {
return progress;
}
public void setProgress(ProgressBar progress) {
this.progress = progress;
}
public void playTimer(){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone ring = RingtoneManager.getRingtone(getApplicationContext(), notification);
ring.play();
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
protected void onStop() {
customHandler.removeCallbacks(updateTimerThread);
super.onStop();
}
}
So now i need a method to stop the alarm when the user presses the Reset Button. Please suggest.
One way to do it is as follows:
Define a boolean inside your Runnable and check it before doing anything in run().
Flip it using a method inside your Runnable.
Here is the code snippet:
private Runnable updateTimerThread = new Runnable() {
private volatile boolean flag = true;
public void stopTimer() {
this.flag = false;
}
#Override
public void run() {
while(flag) {
//long totalMilliseconds = 1500000;
//while (!stopped){
//long totalMilliseconds = 15000;
//updatedTime = totalMilliseconds - SystemClock.currentThreadTimeMillis();
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
if (mins == 1 && secs == 0) {
playTimer();
}
}
}
};
Now, you just have to call stopTimer() to stop the Runnable.
Another way could be to handle the InterruptedException in the Runnable and send an interrupt from the main program.
If I understood question right,you can try to stop alarm sound by declaring your private Ringtone ring and call ring.stop() method in your onStop() method.
private Ringtone ring;
//...//
public void playTimer(){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
ring = RingtoneManager.getRingtone(getApplicationContext(), notification);
ring.play();
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
protected void onStop() {
customHandler.removeCallbacks(updateTimerThread);
ring.stop();
super.onStop();
}
I got a problem with CountDownTimer's StartButton: the timer doesn't start after pressing the button. How do I fix that?
I want to start the timer by pressing button buttonCount.
Can someone help me please?
int clicks = 0;
TextView textCount;
ImageButton buttonCount;
int guessCount =0;
boolean started = false;
boolean timerProcessing = false;
private CountDownTimer count;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newgame);
count = new CountDownTimer(15000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) ((millisUntilFinished / 1000));
textic.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText("Time's Up!");
buttonCount.setEnabled(false);
if (clicks > oldscore)
getSharedPreferences("myPrefs", MODE_PRIVATE).edit().putInt("highscore", clicks).commit();
}
};
final int oldscore = getSharedPreferences("myPrefs", MODE_PRIVATE).getInt("highscore", 0);
final TextView textView = (TextView) findViewById(R.id.applesEaten);
buttonCount = (ImageButton) findViewById(R.id.button);
buttonCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
clicks++;
textView.setText("Clicks: " + clicks);
TextView textView = (TextView) findViewById(R.id.topScoreView);
textView.setText("Best: " + oldscore);
if(!started){
count.start();
started = true;
timerProcessing = true;
}
}
});
final TextView textic = (TextView) findViewById(R.id.textView2);
}
It seems to me this is what you really want to do:
private int clicks = 0;
private TextView textCount;
private ImageButton buttonCount;
private int guessCount = 0;
private CountDownTimer count; // RENAMED
private boolean started = false; // FALSE.
private boolean timerProcessing = false;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newgame);
count = new CountDownTimer(15000, 1000) { // MOVED UP
public void onTick(long millisUntilFinished) {
int seconds = (int) ((millisUntilFinished / 1000));
textic.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText("Time's Up!");
buttonCount.setEnabled(false);
if (clicks > oldscore)
getSharedPreferences("myPrefs", MODE_PRIVATE).edit().putInt("highscore", clicks).commit();
}
};
final int oldscore = getSharedPreferences("myPrefs", MODE_PRIVATE).getInt("highscore", 0);
final TextView textView = (TextView) findViewById(R.id.applesEaten);
buttonCount = (ImageButton) findViewById(R.id.button);
buttonCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
clicks++;
textView.setText("Clicks: " + clicks);
TextView textView = (TextView) findViewById(R.id.topScoreView);
textView.setText("Best: " + oldscore);
if(!started){
count.start(); // START COUNTDOWN TIMER
started = true;
timerProcessing = true;
}
}
});
final TextView textic = (TextView) findViewById(R.id.textView2);
}
And if you really want to start another CountDownTimer than the one you create at the bottom (named count). Then you need to instantiate it and set its behaviour, just like you do for the other CountownTimer.
Also, all the variables you use need to be created before (textic, oldscore)
I've searched everywhere for an answer to this dilemma. A CountDownTimer(bsCountDownTimer) will not start when it should. When I click the button, it is supposed to begin the onTick(), correct? However, only after I navigate to a different activity and navigate backwards using the UP button, or exit the app or destroy it and restart it does the onTick() start updating the text and sending information to LogCat like it is told to do.
My best guess is that this problem is exclusive to either the CDT sub-class, onBsButtonClick(), onCreate(), or possible onResume()/onPause().
Here is some of the source code.
public class HomeActivity extends Activity {
#SuppressLint("NewApi") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
if(bsTimeStamp!=0){bsIsRunning=true;}
if(bsTimeStamp==0){bsIsRunning=false;}
lastFed=(TextView)findViewById(R.id.lastFedTextView);
feedAt=(TextView)findViewById(R.id.feedAtTextView);
daysText = (EditText)findViewById(R.id.editTextDays);
hoursText = (EditText)findViewById(R.id.editTextHours);
minutesText = (EditText)findViewById(R.id.editTextMinutes);
daysText.setText("");
hoursText.setText("");
minutesText.setText("");
// get timeStamp and boolean from onFeedButtonClick() START
final SharedPreferences prefs = this.getPreferences(Context.MODE_PRIVATE);
feedClickTimeStamp = prefs.getLong("savedOnFeedClick", placeholder);
bsTimeStamp = prefs.getLong("savedOnBsClick", bsProgress);
bsPlaceholder = prefs.getLong("saved placeholder", bsPlaceholder);
bsIsRunning = prefs.getBoolean("bs is running", bsIsRunning);
progressbs = Long.toString(bsProgress);
placeholderbs = Long.toString(bsPlaceholder);
timestampbs = Long.toString(bsTimeStamp);
timestamp = Long.toString(feedClickTimeStamp);
LAST_FED = prefs.getString("lastFed", LAST_FED);
FEED_AT = prefs.getString("feedAt", FEED_AT);
feedAt.setText("Feed at: " + FEED_AT);
lastFed.setText("Last fed at: " + LAST_FED);
// get timeStamp and boolean from onFeedButtonClick() END
DateTime date = new DateTime();
long currentTime = date.getMillis();
Long bsDiffInMillis;
if(bsIsRunning=false) {
bsDiffInMillis = 0L;
}
else {
bsDiffInMillis = currentTime - bsTimeStamp;
bsPlaceholder -= bsDiffInMillis;
}
Integer bsDiffInt = Integer.valueOf(bsDiffInMillis.intValue());
int roundedDiff = (bsDiffInt + 500) / 1000 * 1000;
j += roundedDiff - 2000;
// BS PROGRESS BAR START
bsProgressBar = (ProgressBar)findViewById(R.id.bsProgressBar);
bsProgressBar.setProgress(j);
Long bsPlaceholderLong = bsPlaceholder;
final Integer setMax = Integer.valueOf(bsPlaceholderLong.intValue());
bsProgressBar.setMax(setMax);
setProgressBarVisibility(true);
if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB){
bsProgressBar.setRotation(180);
} else{
// FIND A WAY TO ROTATE PROGRESSBAR BEFORE API 11 (3.0)
}
timeDisplayBs=(TextView)findViewById(R.id.bs_countdown); ((TextView)findViewById(R.id.bs_countdown)).setText(convertMillisForCrafting(bsPlaceholder-ji));
millisInFuture = bsPlaceholder;
bsCountDownTimer = new CDT(millisInFuture, countDownInterval);
// START BS BUTTON LISTENER //
final Button startBsBtn = (Button) findViewById(R.id.bsButton);
startBsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBsButtonClick(view);
} //close onClick
}); //close onClickListener
// END BS BUTTON LISTENER //
if (savedInstanceState != null) {} else {}
}// onCreate END
#Override
protected void onPause() {
super.onPause();
bsCountDownTimer.cancel();
}
#SuppressLint("NewApi") #Override
protected void onResume() {
super.onResume();
SharedPreferences prefs = this.getPreferences(Context.MODE_PRIVATE);
bsIsRunning = prefs.getBoolean("bs is running", bsIsRunning);
if(feedClickTimeStamp>0){
mountCountDownTimer.start();
}
if(bsIsRunning==true) {
bsCountDownTimer.start();
bsIsRunning=true;
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("bs is running", bsIsRunning).commit();
}
if(bsIsRunning==false){
bsIsRunning=false;
String progressBarTitleBs = "blacksmithing research";
timeDisplayBs = (TextView)findViewById(R.id.bs_countdown);
timeDisplayBs.setText(progressBarTitleBs.toUpperCase(preferredLocale));
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("bs is running", bsIsRunning).commit();
}
}
public class CDT extends CountDownTimer {
public CDT(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
millisInFuture = prefs.getLong("saved placeholder", bsPlaceholder);
timeDisplayBs=(TextView)findViewById(R.id.bs_countdown);
}
#Override
public void onTick(long millisInFuture) {
Log.v("bsTimer", "Tick of Progress " + ji + " " + millisInFuture);
ji+=1;
j+=1000;
bsProgressBar.setProgress(j);
timeDisplayBs.setText(convertMillisForCrafting(millisInFuture-ji));
}
#Override
public void onFinish() {
bsCountDownTimer.cancel();
j=0;
ji=0;
bsPlaceholder = 0;
bsTimeStamp = 0;
bsProgressBar.setProgress(0);
String progressBarTitleBs = "blacksmithing research";
timeDisplayBs = (TextView)findViewById(R.id.bs_countdown);
timeDisplayBs.setText(progressBarTitleBs.toUpperCase(preferredLocale));
}
}
public void onBsButtonClick(View view) {
final SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
bsTimeStamp = prefs.getLong("savedOnBsClick", bsProgress);
bsPlaceholder = prefs.getLong("saved placeholder", bsPlaceholder);
bsIsRunning = prefs.getBoolean("bs is running", bsIsRunning);
EditText daysText = (EditText)findViewById(R.id.editTextDays);
EditText hoursText = (EditText)findViewById(R.id.editTextHours);
EditText minutesText = (EditText)findViewById(R.id.editTextMinutes);
int daysPh;
int hoursPh;
int minutesPh;
String daysStr = daysText.getText().toString();
String hoursStr = hoursText.getText().toString();
String minutesStr = minutesText.getText().toString();
if (daysStr.matches("") && hoursStr.matches("") && minutesStr.matches("")) {
Toast.makeText(this, "You did not enter DAYS, HOURS, or MINUTES.", Toast.LENGTH_LONG).show();
return;
}
if(bsIsRunning==false){
bsPlaceholder = 0;
bsTimeStamp = 0;
bsIsRunning=true;
j=0;
bsProgressBar.setProgress(0);
Long bsPlaceholderLong = bsPlaceholder;
final Integer setMax = Integer.valueOf(bsPlaceholderLong.intValue());
bsProgressBar.setMax(setMax);
if(daysText.getText().toString().equals("")){
daysText.setText("0");
}
if(hoursText.getText().toString().equals("")){
hoursText.setText("0");
}
if(minutesText.getText().toString().equals("")){
minutesText.setText("0");
}
daysPh = Integer.parseInt(daysText.getText().toString());
hoursPh = Integer.parseInt(hoursText.getText().toString());
minutesPh = Integer.parseInt(minutesText.getText().toString());
daysText.setText("");
hoursText.setText("");
minutesText.setText("");
SharedPreferences.Editor editor = prefs.edit();
bsPlaceholder = getMillisForCrafting(daysPh, hoursPh, minutesPh);
millisInFuture = bsPlaceholder; //VITAL
DateTime dt = new DateTime();
bsProgress = dt.getMillis();
editor.putBoolean("bs is running", bsIsRunning).commit();
editor.putLong("savedOnBsClick", bsProgress).commit();
editor.putLong("saved placeholder", bsPlaceholder).commit();
bsCountDownTimer.start();
} //close if bsIsRunning==false
else if(bsIsRunning==true){
view.invalidate();
new AlertDialog.Builder(HomeActivity.this)
.setTitle("New Blacksmithing Research Timer? (erases current)")
.setMessage("Are you sure you want to start a new timer? \n(Current timer will be erased.)")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
bsPlaceholder = 0;
bsTimeStamp = 0;
bsCountDownTimer.cancel();
bsIsRunning=true;
j=0;
bsProgressBar.setProgress(0);
String progressBarTitleBs = "blacksmithing research";
timeDisplayBs = (TextView)findViewById(R.id.bs_countdown);
timeDisplayBs.setText(progressBarTitleBs.toUpperCase(preferredLocale));
EditText daysText = (EditText)findViewById(R.id.editTextDays);
EditText hoursText = (EditText)findViewById(R.id.editTextHours);
EditText minutesText = (EditText)findViewById(R.id.editTextMinutes);
if(daysText.getText().toString().equals("")){
daysText.setText("0");
}
if(hoursText.getText().toString().equals("")){
hoursText.setText("0");
}
if(minutesText.getText().toString().equals("")){
minutesText.setText("0");
}
int daysPh = Integer.parseInt(daysText.getText().toString());
int hoursPh = Integer.parseInt(hoursText.getText().toString());
int minutesPh = Integer.parseInt(minutesText.getText().toString());
SharedPreferences.Editor editor = prefs.edit();
bsPlaceholder = getMillisForCrafting(daysPh, hoursPh, minutesPh);
DateTime dt = new DateTime();
bsProgress = dt.getMillis();
editor.putBoolean("bs is running", bsIsRunning).commit();
editor.putLong("savedOnBsClick", bsProgress).commit();
editor.putLong("saved placeholder", bsPlaceholder).commit();
Long bsPlaceholderLong = bsPlaceholder;
final Integer setMax = Integer.valueOf(bsPlaceholderLong.intValue());
bsProgressBar.setMax(setMax);
daysText.setText("");
hoursText.setText("");
minutesText.setText("");
bsCountDownTimer.start();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}return;
}
public static Long getMillisForCrafting(int daysPh, int hoursPh, int minutesPh) {
Locale.getDefault();
DateTime bs = new DateTime();
daysPulled = daysPh;
hoursPulled = hoursPh;
minutesPulled = minutesPh;
final long nowInMillis = bs.getMillis();
long days = daysPulled * 86400000;
long hours = hoursPulled * 3600000;
long minutes = minutesPulled * 60000;
long millisToAddToNow = days + hours + minutes;
long futureDateInMillis = millisToAddToNow + nowInMillis;
long millisFromDate = futureDateInMillis - nowInMillis;
return millisFromDate;
}
public void onBsResetButtonClick(View view) {
final SharedPreferences prefs = this.getPreferences(Context.MODE_PRIVATE);
bsTimeStamp = prefs.getLong("savedOnBsClick", bsProgress);
new AlertDialog.Builder(this)
.setTitle("Reset Timer?")
.setMessage("Reset Blacksmithing Research timer? \n(Current timer will be erased.)")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
j=0;
bsProgressBar.setProgress(0);
bsCountDownTimer.cancel();
bsIsRunning=false;
String progressBarTitleBs = "blacksmithing research";
timeDisplayBs = (TextView)findViewById(R.id.bs_countdown);
timeDisplayBs.setText(progressBarTitleBs.toUpperCase(preferredLocale));
bsPlaceholder = 0;
bsTimeStamp = 0;
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("bs is running", bsIsRunning).commit();
editor.putLong("savedOnBsClick", 0).commit();
editor.putLong("saved placeholder", 0).commit();
// CLEAR INPUT EDITTEXT AREAS
EditText daysText = (EditText)findViewById(R.id.editTextDays);
EditText hoursText = (EditText)findViewById(R.id.editTextHours);
EditText minutesText = (EditText)findViewById(R.id.editTextMinutes);
daysText.setText("");
hoursText.setText("");
minutesText.setText("");
// CLEAR INPUT EDITTEXT AREAS
}})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
#SuppressLint("DefaultLocale")
public static String convertMillis(long milliseconds){
long seconds, minutes, hours;
seconds = milliseconds / 1000;
minutes = seconds / 60;
seconds = seconds % 60;
hours = minutes / 60;
minutes = minutes % 60;
Locale.getDefault();
String time = String.format("%02d:%02d:%02d", hours, minutes, seconds);
return(time);
}
#SuppressLint("DefaultLocale")
public static String convertMillisForCrafting(long milliseconds){
long seconds, minutes, hours, days;
seconds = milliseconds / 1000;
minutes = seconds / 60;
seconds = seconds % 60;
hours = minutes / 60;
days = hours / 24;
hours = hours % 24;
minutes = minutes % 60;
Locale.getDefault();
String timeBs = String.format("%02d days %02d hours %02d minutes %02d seconds", days, hours, minutes, seconds);
return(timeBs);
}
#Override
protected void onDestroy() {
super.onDestroy(); // Always call the superclass
mProgressBar.destroyDrawingCache();
mountCountDownTimer.cancel();
// bsProgressBar.destroyDrawingCache();
// bsCountDownTimer.cancel();
// android.os.Debug.stopMethodTracing(); // Stop method tracing that the activity started during onCreate()
}
}
I got it!
The countDownTimer wouldn't start because the variable from onBsButtonClick() (bsPlaceholder) wasn't being passed into onCreate() correctly.
Here's what I did:
Declared a global variable
static long timeInput;
Created a sub-class that extends CountDownTimer:
public class bsTimer extends CountDownTimer {
public bsTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisInFuture) {
Log.v("bsTimer", "Tick of Progress " + ji + " " + millisInFuture);
ji+=1;
j+=1000;
bsProgressBar.setProgress(j);
((TextView)findViewById(R.id.bs_countdown)).setText(convertMillisForCrafting(millisInFuture-ji));
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
}
Instantiated the countdown timer in onCreate();
bsCountDownTimer = new bsTimer(timeInput, 1000);
Then just made a new timer and started it in the onBsButtonClick() method!
bsCountDownTimer = new bsTimer(timeInput, 1000).start();