android timer makes the app crash - android

I'm trying to create a Timer that does something after 5 seconds.
Now in my main activity ( I only got 1 ) I wrote this class:
class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
textFeedback.setText("test");
timer.cancel();
}
}
}
In a function (and also in my mainactivity) I create a timer as new Reminder(5).
After 5 seconds the application crashes.
I don't see whats wrong, because I do it in normal java apps like this.

Not sure where you have initialized textFeedback.
textFeedback.setText("test"); cannot update ui from a timer task. Timer task runs on a non ui thread. Ui can be updated only on ui thread.
Your options use a Handler or runOnUiThread.
Note runOnUiThread is a method of Activity class. Requires Activity Context
More info
Android Thread for a timer

Thanks.
Solved it like this:
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
//textFeedback.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
textFeedback.setText("");
}
}.start();

when the class Remainder is istatiate not know the var textFeedback , becaouse you nees to pass the owmer of the textFeedback

Related

can not run countdowntimer at all

I have a problem with countdown timer.I try some of solutions and articles in this site but they never worked for me. so, please read my codes...
also I used
handler.postDelayed(new Runnable() {
before and it was not my solution but it just worked correctly.
Main question is:
I want to do something like below:
(button pressed)
do some codes1
delay1
do other codes2
delay2
go back to *do some codes1* again.
In short, this is my real code:
itimesec--;
setdelay();
irepeat--;
setrelax();
and this is in my functions:
public void setrelax(){
CountDownTimer yourCountDownTimer1 = new CountDownTimer(50000, 1000) {
public void onTick(long millisUntilFinished1) {
itotalsnozee--;
TextToSpeechFunction(" "+itotalsnozee);
}
public void onFinish() {
itotalsnozee=fitotalsnozee;
isrelax=false;
TextToSpeechFunction("do again");
}
}.start();
yourCountDownTimer1.cancel();
}
I tried to use a variable insted of 50000 but it was not useful anyway.
I tried to put setrelax funtion codes directly into oncreate but it never worked.
it just jumped to
}.start();
yourCountDownTimer1.cancel();
every times and go out.
I tried all the codes without any delay function and they runned correctly.
what is my wrong please...
You need to remember that your code won't be executed sequentially when using the CountDownTimer because it's working asynchronously (via Handler).
Let's dissect your code. Your following code here:
public void setrelax(){
// 1. Creating CountDownTimer
CountDownTimer yourCountDownTimer1 = new CountDownTimer(50000, 1000) {
public void onTick(long millisUntilFinished1) {
// 2. onTick called
...
}
public void onFinish() {
// 3. onFinish called
...
}
}.start();
// 4. CountDownTimer is cancelled.
yourCountDownTimer1.cancel();
}
will be running in the following sequences:
Creating CountDownTimer
CountDownTimer is cancelled.
onTick called 49 times repeatedly (50000/1000 = 50 - 1 ).
onFinish called
So, change your algorithm to something like this:
do some codes1
delay1
--> When delay finished, do other codes2. Then do delay2
You need to call the next code in the CountDownTimer.onFinish()
I looked at your code and I could not find any big mistakes but try this instead
Instead of
.start();
use
yourCountDownTimer1.start();
and remove yourCountTimer1.cancel();
like this :
public void setrelax(){
CountDownTimer yourCountDownTimer1 = new CountDownTimer(50000, 1000) {
public void onTick(long millisUntilFinished1) {
itotalsnozee--;
TextToSpeechFunction(" "+itotalsnozee);
}
public void onFinish() {
itotalsnozee=fitotalsnozee;
isrelax=false;
TextToSpeechFunction("do again");
}
};yourCountDownTimer1.start();
}
Hope it helps.
below is the code for running otp timer in our code.you can copy paste i have mentioned the comments please follow the same.
CountDownTimer countDownTimer; //define countDownTimer
countDownTimer.start(); // start countdown timer on some event like on click
String x="Your code will expire In";
String y="mins";
counttimer(); call the method counttimer which includes all the code of timer
public void counttimer(){
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
String text = String.format(Locale.getDefault(), x+" %02d : %02d "+y,
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60);
phonever_timer.setText(text); //set timer into textview object
}
public void onFinish() {
phonever_timer.setText("Otp Expired..!");
}
};

How can i set any function to repeat after specific amount of time?

public void scheduleAtFixedRate (TimerTask task, long delay, long period). This looks promising but i have no idea how to use it. Any help would be appreciated.It was on android developer site.
Maybe this demo helps you:
import java.util.*;
public class TimerDemo {
public static void main(String[] args) {
TimerTask tasknew = new TimerScheduleFixedRateDelay();
Timer timer = new Timer();
timer.scheduleAtFixedRate(tasknew, 500, 1000);
}
public void run() {
System.out.println("working at fixed rate delay");
}
}
You need to have a method called "run" in your class, that will be repeately executed.
Source.
You can create a timer task and schedule it at a fixed rate like this:
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
// This method is called in a fixed interval
}
};
timer.scheduleAtFixedRate(task, delay, period);
If you need to interact with the UI in the TimerTask you should do it like this:
TimerTask task = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// Interact with UI here
}
});
}
};
public void scheduleAtFixedRate(TimerTask task,
long delay,
long period)
Android doc here.
Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
The task (TimerTask) is the code which will be executed forever, every period milliseconds. Delay is the time (in ms or Date if you want) which the Timer should wait until the start of the TimerTask.
You should remember Timer will run in a different thread from UI thread, so if you need to update the UI you should use runOnUiThread etc. (See Xaver Kapeller answer)
It could be an example
TimerTask tasknew = new TimerTask()
{
#Override
public void run()
{
/* Something here */
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(tasknew, 500, 1000);
I noticed here everyone just posted an example so it's just an extension with an explanation.

how to set a cancellable timeout in android

In my application i want to set a timeout when the user turn on 3G... after a certain amount of time elapsed , i will turn off 3G..
my problem is cancelling the scheduled timer.. every time i call timer.cancel() .. the program throws errors
the problem cause when i call clearTimeout() method..
Timer timer;
class RemindTask extends TimerTask {
public void run() {
//do something when time's up
log("timer","running the timertask..");//my custom log method
timer.cancel(); //Terminate the timer thread
}
}
public void setTimeout(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
public void clearTimeout(){
log("timer", "cancelling the timer task");//my custom log method
timer.cancel();
timer.purge();
}
please help me .. i am an android beginner..
Android has a class CountdownTimer which has start() and cancel().

how to stop/cancel android CountDownTimer

I'm extending the CountDownTimer class to obtain some custom functionality .In onTick() in case some conditions are met I call cancel() , expecting that will be the end of it, however the onTick() callback gets call until the the count down is reached . So how to prevent this from happening ?
CountDownTimer.cancel() method seems to be not working. Here's another thread without a solution Timer does not stop in android.
I would recommend you to use Timer instead. It's much more flexible and can be cancelled at any time. It may be something like that:
public class MainActivity extends Activity {
TextView mTextField;
long elapsed;
final static long INTERVAL=1000;
final static long TIMEOUT=5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextField=(TextView)findViewById(R.id.textview1);
TimerTask task=new TimerTask(){
#Override
public void run() {
elapsed+=INTERVAL;
if(elapsed>=TIMEOUT){
this.cancel();
displayText("finished");
return;
}
//if(some other conditions)
// this.cancel();
displayText("seconds elapsed: " + elapsed / 1000);
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, INTERVAL, INTERVAL);
}
private void displayText(final String text){
this.runOnUiThread(new Runnable(){
#Override
public void run() {
mTextField.setText(text);
}});
}
}
CountDownTimer is also working fine for me, but I think it only works if you call it OUTSIDE of the CountDownTimer implemetation (that is don't call it in the onTick).
Calling it inside also didn't worked.
I tried this code snippet, since most answers are saying you cannot cancel the timer inside its implementation, thus i tried using a handler inside onFinish. Old post but if anyone comes across this its helpful.
new Handler().post(new Runnable() {
#Override
public void run() {
timerTextView.setText("00:" + String.format("%02d", counter));
cancel();
}
});

Android CountDownTimer

When writing :
CountDownTimer timer = new CountDownTimer(1000, 100)
{
#Override
public void onTick(long l)
{
}
#Override
public void onFinish()
{
};
}.start();
are we actually starting a new thread that handles ticks? If not, what is really happening?
CountDownTimer's implementation uses Handler and sendMessageDelayed(), so no background thread is needed. This does mean that the timer will not update if you are tying up the main application thread elsewhere in your code.
Definition from multiple publications, tried and tested:
"Another timer is provided with the built-in class CountDownTimer.This encapsulates the creation of a background thread and the handler queuing into a convenient class call..."

Categories

Resources