Java countdown timer - one after another - java

I am supernoob programmer. I'm trying to make an adroid interval timer, where user inputs rounds, work time and break time. I can't find a way to start break timer after work timer, they start running at the same time. How should I go about it?
Thanks!
public class MainActivity extends Activity {
EditText rundy, praca, przerwa;
Button start;
TextView timer;
boolean timerHasStarted = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rundy = (EditText) findViewById(R.id.rundy); // rounds
praca = (EditText) findViewById(R.id.praca); // work time
przerwa = (EditText) findViewById(R.id.przerwa); // break time
start = (Button) findViewById(R.id.start);
timer = (TextView) findViewById(R.id.timer);
start.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int rundyL = Integer.parseInt(rundy.getText().toString())*1000;
long pracaL = Long.parseLong(praca.getText().toString()) * 1000;
long przerwaL = Long.parseLong(przerwa.getText().toString())*1000;
MyCountDownTimer countDownTimerPraca = new MyCountDownTimer(pracaL, 1000);
MyCountDownTimer countDownTimerPrzerwa = new MyCountDownTimer(przerwaL,1000);
for(int i = 0; i<rundyL; i++){
countDownTimerPraca.start();
countDownTimerPrzerwa.start();
}
}
class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long pracaL, long interval) {
super(pracaL, interval);
}
#Override
public void onTick(long millisUntilFinished) {
timerHasStarted = true;
long minutes = (millisUntilFinished / 1000)/60;
long seconds = (millisUntilFinished/1000)%60;
timer.setText( String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
}
#Override
public void onFinish() {
timerHasStarted = false;
timer.setText("Times up");
}
}
});
}
}

public class MainActivity extends Activity {
EditText rundy, praca, przerwa;
Button start;
TextView timer;
boolean timerHasStarted = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rundy = (EditText) findViewById(R.id.rundy); // rounds
praca = (EditText) findViewById(R.id.praca); // work time
przerwa = (EditText) findViewById(R.id.przerwa); // break time
start = (Button) findViewById(R.id.start);
timer = (TextView) findViewById(R.id.timer);
start.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int rundyL = Integer.parseInt(rundy.getText().toString())*1000;
long pracaL = Long.parseLong(praca.getText().toString()) * 1000;
long przerwaL = Long.parseLong(przerwa.getText().toString())*1000;
MyCountDownTimer countDownTimerPrzerwa = new MyCountDownTimer(przerwaL,1000);
MyCountDownTimer countDownTimerPraca = new MyCountDownTimer(countDownTimerPrzerwa,pracaL, 1000);
for(int i = 0; i<rundyL; i++){
countDownTimerPraca.start();
}
}
class MyCountDownTimer extends CountDownTimer {
private MyCountDownTimer mytimer;
public MyCountDownTimer(long pracaL, long interval) {
super(pracaL, interval);
}
public MyCountDownTimer(MyCountDownTimer timer, long pracaL, long interval) {
this(pracaL, interval);
this.timer = timer;
}
#Override
public void onTick(long millisUntilFinished) {
timerHasStarted = true;
long minutes = (millisUntilFinished / 1000)/60;
long seconds = (millisUntilFinished/1000)%60;
timer.setText( String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
}
#Override
public void onFinish() {
timerHasStarted = false;
timer.setText("Times up");
if(mytimer!=null)
mytimer.start();
}
}
});
}
}

Related

How can I let my Timer Count when I change the activity to keep counting the time in Android Studio?

I going to fix the issue about when I click the to go another activity and my timer started before, when I back to the timer count activity, the timer stopped and auto reset to 0. How can I manage the activity when I back to timer activity and keep the timer counting?
Here are my code of my timer counter.
// TimerCount
TextView txtvTimer;
Button pauseStartBtn;
Button stopFinishBtn;
boolean timerStarted = false;
Timer timer;
TimerTask timerTask;
Double time = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer_count);
Log.d(TAG_LIFECYCLE, "In the activity_timer_count onCreate() event");
// timer
txtvTimer = (TextView) findViewById(R.id.txtvTimer);
pauseStartBtn = (Button) findViewById(R.id.btnStartPause);
stopFinishBtn = (Button) findViewById(R.id.btnStopFinish);
stopFinishBtn.setEnabled(false);
timer = new Timer();
// bottom nav
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav);
bottomNavigationView.setSelectedItemId(R.id.timerCountActivity);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.mainActivity:
startActivity(new Intent(getApplicationContext(),MainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.mapActivity:
startActivity(new Intent(getApplicationContext(),MapActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.timerCountActivity:
return true;
case R.id.userInfoActivity:
startActivity(new Intent(getApplicationContext(),UserInfoActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.settingActivity:
startActivity(new Intent(getApplicationContext(),SettingActivity.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
}
// timer reset button
public void resetTapped(View v) {
AlertDialog.Builder resetAlert = new AlertDialog.Builder(this);
resetAlert.setTitle("Reset Timer");
resetAlert.setMessage("Reset the timer?");
resetAlert.setPositiveButton("Reset", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (timerTask != null) {
timerTask.cancel();
setButton("START", R.color.green);
time = 0.0;
timerStarted = false;
txtvTimer.setText(formatTime(0,0,0));
}
}
});
resetAlert.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
resetAlert.show();
}
// timer start pause button
public void startPauseTapped(View v) {
if (timerStarted == false){
timerStarted = true;
setButton("PAUSE", R.color.red);
startTimer();
onStartClicked(v);
onLocateClicked(v);
stopToPushData(v);
} else {
timerStarted = false;
setButton("Resume", R.color.green);
timerTask.cancel();
onStartClicked(v);
onLocateClicked(v);
}
}
private void setButton(String start, int color) {
pauseStartBtn.setText(start);
pauseStartBtn.setTextColor(ContextCompat.getColor(this, color));
}
private void startTimer() {
timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
time++;
txtvTimer.setText(getTimerText());
}
});
}
};
timer.scheduleAtFixedRate(timerTask,0,1000);
}
private String getTimerText() {
int rounded = (int) Math.round(time);
int seconds = ((rounded % 86400) % 3600) % 60;
int minutes = ((rounded % 86400) % 3600) / 60;
int hours = ((rounded % 86400) / 3600) ;
return formatTime (seconds, minutes, hours);
}
private String formatTime(int seconds, int minutes, int hours) {
return String.format("%02d",hours) + " : " + String.format("%02d",minutes) + " : " + String.format("%02d",seconds);
}
Second, how can I get the timer to calculate the time per second?
Is it rounded % 86400 will be the real second I have counted?
I think it's better to use chronometer
Xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<Chronometer
android:id="#+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Main Acitvity:
public class MainActivity extends AppCompatActivity {
Chronometer chronometer ;
long stopTime ; // this variable will count the time when stop counting (when you have left the activity)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chronometer = (Chronometer) findViewById(R.id.chronometer);
}
void StartCounting() {
chronometer.setBase(SystemClock.elapsedRealtime()-stopTime); // This line will set the time to correct when you return to the activity
chronometer.start();
}
void PauseCounting() {
stopTime = SystemClock.elapsedRealtime()-chronometer.getBase();
chronometer.stop();
}
}

Displaying timer of an alarm using button

I have this code where I made 2 buttons, one to set an alarm and one for checking the time left until the alarm going off. Currently, I'm struggling with the second button which checking the timer. Can someone help me out?
Here's my code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
Button button2 = (Button) findViewById(R.id.button2);
final TextView lefty = (TextView)findViewById(R.id.left);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
Long preTime = calendar.getTimeInMillis();
calendar.add(Calendar.HOUR_OF_DAY,8);
Long postTime = calendar.getTimeInMillis();
Long delay = postTime - preTime;
Intent intent = new Intent(getApplicationContext(),NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
CountDownTimer timer = new CountDownTimer(delay, 1) {
#Override
public void onTick(long millisUntilFinished) {
final int seconds = (int) (millisUntilFinished / 1000) % 60;
final int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
final int hour = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
runOnUiThread(new Runnable() {
#Override
public void run() {
lefty.setText( hour + " : " + minutes + " : " + seconds);
}
});
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
};
timer.start();
}
});
button2.setOnClickListener(new View.OnClickListener() {
"some code"
}
}
For do my answer and help you, i will completing your code and add a TextView for exemple for put the time on it.
public class MainActivity extends AppCompatActivity {
// modify here
private Calendar myTimer = null;
private TextView myTextView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
Button button2 = (Button) findViewById(R.id.button2);
final TextView lefty = (TextView)findViewById(R.id.left);
// modify here
myTextView = (TextView) findViewById(R.id.my_text_view);
myTimer = Calendar.getInstance();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
Long preTime = calendar.getTimeInMillis();
calendar.add(Calendar.HOUR_OF_DAY, 8);
Long postTime = calendar.getTimeInMillis();
Long delay = postTime - preTime;
Intent intent = new Intent(getApplicationContext(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
CountDownTimer timer = new CountDownTimer(delay, 1) {
#Override
public void onTick(long millisUntilFinished) {
final int seconds = (int) (millisUntilFinished / 1000) % 60;
final int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
final int hour = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
// modify here
myTimer.set(Calendar.SECOND, seconds);
myTimer.set(Calendar.MINUTE, minutes);
myTimer.set(Calendar.HOUR, hour);
runOnUiThread(new Runnable() {
#Override
public void run() {
lefty.setText(hour + " : " + minutes + " : " + seconds);
}
});
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
};
timer.start();
}
});
// modify here
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myString = new SimpleDateFormat("hh : mm : ss").format(myTimer);
myTextView.setText(myString);
}
});
}
}

Unable to set timer in Snackbar

I am trying to set a timer in my Snackbar, I have tried this so far and gotten the timer to work but not in the getTime() method which I think might be the case which is why this isn't working.
I am sorry if this is too bad of a question, I only do Android as a side project.
public class MainActivity extends AppCompatActivity {
private static final String AUDIO_RECORDER_FILE_EXT = ".3gp";
private static final String AUDIO_RECORDER_FOLDER = "VRemind";
private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_format = MediaRecorder.OutputFormat.THREE_GPP;
private String file_ext = AUDIO_RECORDER_FILE_EXT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CountDownTimer t;
t = new CountDownTimer( Long.MAX_VALUE , 1000) {
int cnt=0;
#Override
public void onTick(long millisUntilFinished) {
cnt++;
long millis = cnt;
int seconds = (int) (millis / 60);
setTime(cnt);
Log.d("Count:", ""+cnt);
}
#Override
public void onFinish() {
}
};
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Snackbar snackbar = Snackbar.make(findViewById(R.id.root_layout), getTime(), Snackbar.LENGTH_INDEFINITE);
final FloatingActionButton fabAdd = (FloatingActionButton) findViewById(R.id.fabAdd);
final FloatingActionButton fabStop = (FloatingActionButton) findViewById(R.id.fabStop);
fabAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.start();
fabAdd.setVisibility(View.GONE);
fabStop.setVisibility(View.VISIBLE);
snackbar.show();
snackbar.setAction("CANCEL", new View.OnClickListener() {
#Override
public void onClick(View v) {
snackbar.dismiss();
fabAdd.setVisibility(View.VISIBLE);
fabStop.setVisibility(View.GONE);
}
});
}
});
fabStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.cancel();
snackbar.dismiss();
fabStop.setVisibility(View.GONE);
fabAdd.setVisibility(View.VISIBLE);
}
});
}
private String display;
public void setTime(int rawCount) {
int rc = rawCount;
int minutes = (rc - (rc % 60)) / 60;
int seconds = (rc % 60);
String mins = String.format(Locale.ENGLISH, "%02d", minutes);
String secs = String.format(Locale.ENGLISH, "%02d", seconds);
display = mins+ ":" +secs;
Log.d("CountTwo:",display);
getTime();
}
public String getTime() {
Log.d("Count getTime:", display);
return display;
}
Are you getting this message?
java.lang.NullPointerException: println needs a message
If yes it is because you try to log a null message like this:
Log.d("Count getTime:", display);
You have to initialize the display variable to have a value for the first run.
private String display = "";
I looked into it and the problem was that the String display was inaccessible to the Snackbar and also the Snackbar test was unable to update dynamically so I did both of those and made a few changes here and there and here's my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CountDownTimer t;
t = new CountDownTimer( Long.MAX_VALUE , 1000) {
int cnt=0;
#Override
public void onTick(long millisUntilFinished) {
cnt++;
long millis = cnt;
int seconds = (int) (millis / 60);
setTime(cnt);
Log.d("Count:", ""+cnt);
}
#Override
public void onFinish() {
cnt = 0;
}
};
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
snackbar = Snackbar.make(findViewById(R.id.root_layout), "", Snackbar.LENGTH_INDEFINITE);
final FloatingActionButton fabAdd = (FloatingActionButton) findViewById(R.id.fabAdd);
final FloatingActionButton fabStop = (FloatingActionButton) findViewById(R.id.fabStop);
fabAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.start();
fabAdd.setVisibility(View.GONE);
fabStop.setVisibility(View.VISIBLE);
snackbar.show();
snackbar.setAction("CANCEL", new View.OnClickListener() {
#Override
public void onClick(View v) {
t.cancel();
t.onFinish();
// setTime(0);
snackbar.dismiss();
fabAdd.setVisibility(View.VISIBLE);
fabStop.setVisibility(View.GONE);
}
});
}
});
fabStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.cancel();
t.onFinish();
// setTime(0);
snackbar.dismiss();
fabStop.setVisibility(View.GONE);
fabAdd.setVisibility(View.VISIBLE);
}
});
}
/*
public void Duration() {
*//* Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
int count;
#Override
public void run() {
setTime(count);
count++;
Log.d("Count:", ""+count);
}
});
}
};*//* //Old code removed on 22Apr17#11:41PM
}*/ //Old code Duration method
String display="";
public void setTime(int rawCount) {
// int rc = rawCount;
int minutes = (rawCount - (rawCount % 60)) / 60;
int seconds = (rawCount % 60);
String mins = String.format(Locale.ENGLISH, "%02d", minutes);
String secs = String.format(Locale.ENGLISH, "%02d", seconds);
display = mins+ ":" +secs;
Log.d("CountTwo:",display);
snackbar.setText(display);
}
/*public String getTime() {
Log.d("Count getTime:", display);
return display;
}*/

Text does not show string in CountDownTimer

I have a CountDownTimer Class to set a countdown which will start will when the user clicks some Button.
This is the code that includes the CountDownTimer
public class play extends Activity implements View.OnClickListener{
private TapCountDownTimer countDownTimer;
private final long startTime = 10;
private final long interval = 1;
private TextView countdowntext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.play);
countDownTimer = new TapCountDownTimer(startTime, interval);
countdowntext = (TextView)findViewById(R.id.countdowntext);
countdowntext.setText(String.valueOf(startTime));
Button buttonstart = (Button)findViewById(R.id.stopbutton);
buttonstart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
countDownTimer.start();
}
});
Button buttonstop = (Button)findViewById(R.id.stopbutton);
buttonstop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
countDownTimer.cancel();
}
});
public class TapCountDownTimer extends CountDownTimer {
public TapCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onTick(long millisUntilFinished)
{
countdowntext.setText(Long.toString(millisUntilFinished/1));
}
#Override
public void onFinish()
{
countdowntext.setText("Time's up!");
}
}
}
I set the text in this line
countdowntext.setText(Long.toString(millisUntilFinished/1));
But it's not working and the text shows "Time's Up" instead of the countdown.
Does anyone know how to fix this issue?
Your startTime and interval are erroneosly set in seconds.
Just multiply both by 1000, since you need milliseconds.
Also note that you don't need longs, for holding such low values.
Integers will do.
private final int startTime = 10000; // 10 secs
private final int interval = 1000; // 1s = 1000 ms
Also this has no meaning: millisUntilFinished/1 (dividing any number by 1 gives you the original number).
It must be millisUntilFinished / 1000

How to create multiple onClick methods in android

I'm trying to make an application that has multiple buttons, and when each button is pressed, it will start a new timer and display the time on the text view assigned to that button. I have successfully made one of the buttons create a working timer, however I'm having trouble making another button do the same thing for a different text view. I do not know how to create multiple onCLick methods.
EDIT: I'm trying to make wolvesbutton do the same thing as wratihsbutton, but have a separate timer, and display it on a different text view.
Here is what I have so far:
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textView5, textView6, textView7;
long starttime = 0;
//this posts a message to the main thread from our timertask
//and updates the textfield
final Handler h = new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
textView5.setText(String.format("%d:%02d", minutes, seconds));
return false;
}
});
//runs without timer be reposting self
Handler h2 = new Handler();
Runnable run = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
textView5.setText(String.format("%d:%02d", minutes, seconds));
h2.postDelayed(this, 500);
if(seconds >= 10 || minutes >= 1){
textView5.setText("Ready");
}
}
};
//tells handler to send a message
class firstTask extends TimerTask {
#Override
public void run() {
h.sendEmptyMessage(0);
}
};
//tells activity to run on ui thread
class secondTask extends TimerTask {
#Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
textView6.setText(String.format("%d:%02d", minutes, seconds));
}
});
}
};
class wolvesFirstTask extends TimerTask {
#Override
public void run() {
h.sendEmptyMessage(0);
}
};
//tells activity to run on ui thread
class wolvesSecondTask extends TimerTask {
#Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
textView6.setText(String.format("%d:%02d", minutes, seconds));
}
});
}
};
Timer wraiths = new Timer();
Timer wolves = new Timer();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView5 = (TextView)findViewById(R.id.textView5);
textView6 = (TextView)findViewById(R.id.textView5);
Button wraithsbutton = (Button)findViewById(R.id.wraithsb);
Button wolvesbutton = (Button)findViewById(R.id.wolvesb);
wraithsbutton.setText("Start");
wraithsbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button wraithsbutton = (Button)v;
if(wraithsbutton.getText().equals("Stop")){
wraiths.cancel();
wraiths.purge();
h2.removeCallbacks(run);
wraithsbutton.setText("Start");
}else{
starttime = System.currentTimeMillis();
wraiths = new Timer();
wraiths.schedule(new firstTask(), 0,500);
wraiths.schedule(new secondTask(), 0,500);
h2.postDelayed(run, 0);
wraithsbutton.setText("Stop");
}
}
});
}
}
You need to add implement keyword after the extending the class
and then you have to override the onClick method like this
public class Example extends Activity implements OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menulayout);
Button button1 = (Button) findViewById(R.id.b1);
button1.setOnClickListener(this);
Button button2 = (Button) findViewById(R.id.b2);
button2.setOnClickListener(this);
Button button3 = (Button) findViewById(R.id.b3);
button3.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.b1)
{
//do something here if button1 is clicked
}
else if (v.getId() == R.id.b2)
{
//do something here if button2 is clicked
}
else if (v.getId() == R.id.b3)
{
//do something here if button3 is clicked
}
}
}
An unrelated suggestion; I'd pull out the time display into a method, as the same code is in 4 places.
private void showElapsedTime(long elapsedTime, TextView textView) {
int seconds = (int) (elapsedTime / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
textView.setText(String.format("%d:%02d", minutes, seconds));
}
private void showElapsedTimeOnUiThread(final long elapsedTime, final TextView textView) {
runOnUiThread(new Runnable() {
#Override
public void run() {
showElapsedTime(elapsedTime, textView);
}
});
}
Call these methods from the 4 locations.
E.g.
Runnable run = new Runnable() {
#Override
public void run() {
showElapsedTime(System.currentTimeMillis() - starttime, textView5);
and
class secondTask extends TimerTask {
#Override
public void run() {
showElapsedTimeOnUiThread(System.currentTimeMillis() - starttime, textView6));
}
for example.
basically something like this:
public class MyButton extends Button implements View.OnClickListener{
private TextView tv; /// or ArrayList<TextView> tvs;
public MyButton(Context context,TextView tv) {
super(context);
this.tv = tv; ///your text views to be set make as many as you want or pass an array of text views if you like List<? extends TextView> as a constructor param
setOnClickListener(this);
}
public void onClick(View view) {
//run your tasks here
//set the textviews as you like -
}
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
setOnClickListener(this);
}
public MyButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setOnClickListener(this);
}
}
hope it will give you some ideas

Categories

Resources