Where do i add the timer code in my program ? - java

This is my top of my code:
public class MainActivity extends ActionBarActivity
{
private static final int MY_DATA_CHECK_CODE = 0;
public static MainActivity currentActivity;
TextToSpeech mTts;
private String targetURL;
private String urlParameters;
private Button btnClick;
private String clicking = "clicked";
private String[] ipaddresses = new String[]{
"http://10.0.0.1:8098/?cmd=nothing",
"http://192.168.1.10:8098/?cmd=nothing"};
private String iptouse = "";
private TextView text;
private boolean connectedtoipsuccess = false;
private int counter = 0;
private NotificationCompat.Builder mbuilder;
private Timer timer = new Timer();
TextView timerTextView;
long startTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
currentActivity = this;
initTTS();
}
And i want to add this code to my program so when i'm running my program i will the timer running.
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerTextView.setText(String.format("%d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
timerTextView = (TextView) findViewById(R.id.timerTextView);
Button b = (Button) findViewById(R.id.button);
b.setText("start");
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("stop")) {
timerHandler.removeCallbacks(timerRunnable);
b.setText("start");
} else {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
b.setText("stop");
}
}
});
}
#Override
public void onPause() {
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
Button b = (Button)findViewById(R.id.button);
b.setText("start");
}
What i want it to do is once i'm running the program the timer will start.
But i can't find how and where to add this part of the timer code.
I tried in the onCreate and i tried after the onCreate but it give errors since you can just add #override

You will probably want to set up another class (either in the same class or in its own class) and implement Runnable then from your on create make instance to that runnable.

Related

Multiple random number results

Currently working in Android Studio and running into a little trouble. Trying to get my rollScore button to roll over and over. At this point it "rolls" once and stops. I've tried a for loop and while loop and unable to get it to allow multiple "rolls".
public class GameScreen extends AppCompatActivity {
private Button rollButton; // Roll button being declared as a variable
private TextView rollScore; // Text view being declared as a variable
private TextView totalSCore; //
private int mCounter = 0;
private int totalRuns = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen);
Random randomGenerator = new Random();
final int randomInt = randomGenerator.nextInt(7) + 1;
rollButton = (Button) findViewById(R.id.rollButton);
rollScore = (TextView) findViewById(R.id.rollScore);
totalSCore = (TextView) findViewById(R.id.totalScore);
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rollScore.setText(Integer.toString(randomInt));
mCounter++;
}
});
}
}
You have to generate a new random number on each click on your button.
Like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen);
Random randomGenerator = new Random();
int randomInt;
rollButton = (Button) findViewById(R.id.rollButton);
rollScore = (TextView) findViewById(R.id.rollScore);
totalSCore = (TextView) findViewById(R.id.totalScore);
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
randomInt = randomGenerator.nextInt(7) + 1;
rollScore.setText(Integer.toString(randomInt));
mCounter++;
}
});
}
You need to generate a new random number after every roll e.g.
rollScore.setText(Integer.toString(randomGenerator.nextInt(7) + 1));

how to implement Countdown timer with custom starting time?

I have been trying to implement a count down timer using handler in a simple text view. I need to set a custom time. for ex., the timer should start from
06:12:00.
-- This is the MainActivityenter code here code --.
public class MainActivity extends AppCompatActivity {
private Button startButton;
private Button pauseButton;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerValue = (TextView) findViewById(R.id.timerValue);
startButton = (Button) findViewById(R.id.startButton);
--listener for start button --
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
});
pauseButton = (Button) findViewById(R.id.pauseButton);
--listener for pause button--
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});
}
private Runnable updateTimerThread = new Runnable() {
public void run()
{
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
int hours = mins/60;
secs = secs % 60;
timerValue.setText(String.format("%02d", hours)+":" +
(String.format("%02d", mins)) + ":"
+ String.format("%02d", secs) );
customHandler.postDelayed(this, 0);
}
};}
The output i am getting is here https://ibb.co/pd95Yww
public class MainActivity extends AppCompatActivity {
long timeInMilliseconds = 0L;
long timeSwapBuff = 22320000; // 6Hours:12Minutes:00Seconds
long updatedTime = 0L;
private Button startButton;
private Button pauseButton;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
String hms = String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(updatedTime),
TimeUnit.MILLISECONDS.toMinutes(updatedTime) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(updatedTime)),
TimeUnit.MILLISECONDS.toSeconds(updatedTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(updatedTime)));
timerValue.setText(hms);
customHandler.postDelayed(this, 0);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerValue = findViewById(R.id.timer);
startButton = findViewById(R.id.start);
pauseButton = findViewById(R.id.pause);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
});
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});
}
}
I guess the issue is with pause button listener .....
It should be
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwapBuff = timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});

Calling a function every 1.5 seconds after a button is pressed

The function I have created now gives me a random number between 0.8 and 1.2 every time I click on a button within my android application and displays the result in a TextView. However, I would like for this function to keep giving me a new number every 1.5 seconds without having to click on the button continuously for a new result. How would I go about doing this?
Below displays the function I would like to call every 1.5 seconds.
public void generate(View view) {
double min = 0.8;
double max = 1.2;
Random rand = new Random();
double number = rand.nextDouble()* max;
TextView myText = (TextView)findViewById(R.id.textView_RanNum);
String myString = String.valueOf(number);
myText.setText(myString);
}
All help will be greatly appreciated.
You can use Handler / Runnable:
public class MainActivity extends AppCompatActivity {
Handler handler;
Button buttonStart, buttonStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
buttonStart = findViewById(R.id.button);
buttonStop = findViewById(R.id.button2);
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runnable.run();
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.removeCallbacks(runnable);
}
});
}
public Runnable runnable = new Runnable() {
public void run() {
generate();
handler.postDelayed(runnable, 1500); // 1500 miliseconds
}};
public void generate() {
double min = 0.8;
double max = 1.2;
double number;
Random rand = new Random();
TextView myText = findViewById(R.id.textView_RanNum);
number = rand.nextDouble() * max;
String myString = String.valueOf(number);
myText.setText(myString);
}
}
You can use Android's Handler class to do this.
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Handler myHand = new Handler();
myHand.postDelayed(new Runnable() {
#Override
public void run() {
generate();
}
}, 1500);
}
});
}
public void generate() {
double min = 0.8;
double max = 1.2;
Random rand = new Random();
double number = rand.nextDouble() * max;
TextView myText = (TextView) findViewById(R.id.textView_RanNum);
String myString = String.valueOf(number);
myText.setText(myString);
}
}
Read More about Handler here : https://developer.android.com/reference/android/os/Handler

How do I access my CountDownTimer to cancel it in Java?

Making a small game in Android Studio. Basically, the user will have a set amount of time to trigger a button press or the game will end. My CountDownTimer object is inside of a different function than my button click handler. How can I cancel the countDownTimer using cancel() from the button click handler.
Here is my code:
public countDownTimer timeLimit;
public void generate() {
final ProgressBar timer = (ProgressBar)findViewById(R.id.timer);`
int timeoutSeconds = 5000;
timer.setMax(timeoutSeconds);
timeLimit = new CountDownTimer(timeoutSeconds, 100) {
public void onTick(long millisUntilFinished) {
int timeUntilFinished = (int) millisUntilFinished;
timer.setProgress(timeUntilFinished);
}
public void onFinish() {
gameOver();
}
};
timeLimit.start();
}
public void buttonClicked(View v) {
timeLimit.cancel();
}
I'd be happy to hear any alternative ways to do this as well.
The code below works perfectly for me.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ProgressBar progressBar;
private CountDownTimer countDownTimer;
private Button stopTimerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
stopTimerButton = (Button)findViewById(R.id.button);
stopTimerButton.setOnClickListener(this);
int timeoutSeconds = 5000;
progressBar.setMax(timeoutSeconds);
countDownTimer = new CountDownTimer(timeoutSeconds,100) {
#Override
public void onTick(long millisUntilFinished) {
int timeUntilFinished = (int) millisUntilFinished;
progressBar.setProgress(timeUntilFinished);
}
#Override
public void onFinish() {
}
};
countDownTimer.start();
}
#Override
public void onClick(View view) {
if(view == stopTimerButton){
countDownTimer.cancel();
}
}
}

TextView not Displaying Timer

For some reason whenever I try to update my TextView to show how many seconds a person has left. But for some reason now it isn't working.
public class MainActivity extends Activity {
private int index=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
final int[] Times= {6000,3000,7000,3000,4000,6000,3000};
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
final TextView textview =(TextView) findViewById(com.example.countdowntest.R.id.textView);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(index<Times.length){
CountDownTimer timer = new CountDownTimer(
Times[index], 0) {
public void onTick(long millisUntilFinished) {
textview.setText("seconds remaining: "+ millisUntilFinished / 1000);
}
public void onFinish() {
textview.setText("done!");
index++;
}
}.start();
}
}
});
}
}
It should display the updated seconds until it is finished because it is all within the onClick method which doesn't end until the timer reaches zero.
Your countDownInterval is 0
CountDownTimer(long millisInFuture, long countDownInterval)
What you have
new CountDownTimer(Times[index], 0) { // second param to the constructor is 0.
Should be
new CountDownTimer(30000, 1000) // whatever value you like
http://developer.android.com/reference/android/os/CountDownTimer.html
It won't update because you are passing 0 try passing 1000 which will update it at 1 second interval

Categories