cancel countdowntimer on onbackpressed - android

I'm trying to cancel the countdowntimer on onbackpressed, I put counter.cancel; there but "'count' cannot be resolved" error appears. I think It can't find the countdowntimer!
There is a btn_riazi1_1_1 that can cancel the timer.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_riazi1_1);
//// handling timer
final TextView textic = (TextView) findViewById(R.id.riazi1_1_timer);
final CountDownTimer Count = new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
textic.setText(getResources().getString(R.string.remaintime) + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText(getResources().getString(R.string.timesup));
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(Riazi1_1.this,Riazi1_2.class);
startActivity(i);
}
}, 1000);
}
};
Count.start();
/////////////////
//// handling button1
Button btn1 = (Button) findViewById(R.id.btn_riazi1_1_1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Count.cancel();
TextView txtwrong = (TextView) findViewById(R.id.txt_wrong_riazi1_1);
txtwrong.setVisibility(View.VISIBLE);
Button btn2 = (Button) findViewById(R.id.btn_riazi1_1_2);
btn2.setBackgroundColor(Color.GREEN);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(Riazi1_1.this,Riazi1_2.class);
startActivity(i);
}
}, 1000);
}
});
}
#Override
public void onBackPressed(){
super.onBackPressed();
Count.cancel(); // error: Count cannot be resolved ///
}
}

You have declared the TImer within onCreate method. So you cannot access it outside of onCreate. Declare it as a member variable.
private CountDownTimer Count; /// declare it as a member variable
and in the onCreate method initialize it like
Count = new CountDownTimer(5000, 1000).....
[A suggestion, use the naming convension. naming a variable starting with capital letter is really confusing]

Related

CountDownTimer Is Not Cancelling --- Continues to Run After Cancel()

I've implemented a CountDownTimer in my code as follows: At the top of the class, I create
CountDownTimer myTimer;
Then when a user presses button Start, the following method is called:
private void countme()
{
final int tick = 500;
final int countTime = 10000;
myTimer = new CountDownTimer(countTime, tick) {
#Override
public void onTick(final long millisUntilFinished) { }
#Override
public void onFinish() {
myPicture.setVisibility(View.GONE);
}
};
myTimer.start();
}
I have button Stop all myTimer.cancel(). As you can see, if the timer is not cancelled, myPicture will disappear.
Even if I click the stop button so that myTimer.cancel() is called (I checked this with log statements), the counter still continues to count down and to make the picture disappear when it's done.
Why isn't it stopping? How do I get it to actually cancel?
To clarify, I do know how to implement Runnable timers, but they are not as accurate for my needs as CountDownTimers are, which is why I'm not using them in this case.
After a lot of tries, trick is to declare the timer in onCreate but start and cancel it in some other method. The onFinish() will not call after cancelling the timer.
myTimer = new CountDownTimer(COUNT_DOWN_TIME, TICK) {
#Override
public void onTick(final long millisUntilFinished) {
((TextView) findViewById(R.id.textView3)).setText(""
+ millisUntilFinished);
}
#Override
public void onFinish() {
findViewById(R.id.timer_imageBiew).setVisibility(View.GONE);
}
};
private fun startTimer() {
myTimer .start()
}
private fun stopTimer() {
myTimer .cancel()
}
Here in your method countme() you are initializing myTimer, so outside this method myTimer has no value.
Use this
Declare at the top
CountDownTimer myTimer;
final int tick = 500;
final int countTime = 10000;
In the onCreate method of Activity or Fragment
myTimer = new CountDownTimer(countTime, tick) {
#Override
public void onTick(final long millisUntilFinished) { }
#Override
public void onFinish() {
myPicture.setVisibility(View.GONE);
}
};
Now use myTimer.start() to start and myTimer.cancel() to stop it.
Hope you understood.
Your post is very odd. I just tried doing a sample activity:
public class MainActivity extends AppCompatActivity {
CountDownTimer myTimer;
Button btnStart;
Button btnCancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample2);
btnStart = (Button) findViewById(R.id.start);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countme();
Toast.makeText(MainActivity.this, "Count Started!", Toast.LENGTH_SHORT).show();
}
});
btnCancel = (Button) findViewById(R.id.cancel_timer);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myTimer.cancel();
Toast.makeText(MainActivity.this, "Clicked Stop Timer!", Toast.LENGTH_SHORT).show();
}
});
}
private void countme() {
final int tick = 500;
final int countTime = 10000;
myTimer = new CountDownTimer(countTime, tick) {
#Override
public void onTick(final long millisUntilFinished) {
Log.d(MainActivity.class.getSimpleName(), "onTick()");
}
#Override
public void onFinish() {
// myPicture.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "In onFinish()", Toast.LENGTH_SHORT).show();
}
};
myTimer.start();
}
}
It works perfectly fine. It stops the timer. But I went and looked around and found this answer where it mentions that CountDownTimer doesn't seem to work, so he suggested to use a Timer instead. Do check it out. Cheers!
This is working example , I have implemented both handler and timer you can pick one .
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class MainActivity extends Activity {
private CountDownTimer myTimer;
final int TICK = 500;
final int COUNT_DOWN_TIME = 2000;
// Option 2 using handler
private Handler myhandler = new Handler();
private Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Option 1 using timer
myTimer = new CountDownTimer(COUNT_DOWN_TIME, TICK) {
#Override
public void onTick(final long millisUntilFinished) {
((TextView) findViewById(R.id.textView3)).setText(""
+ millisUntilFinished);
}
#Override
public void onFinish() {
findViewById(R.id.timer_imageBiew).setVisibility(View.GONE);
}
};
// Option 2 using handler
runnable = new Runnable() {
#Override
public void run() {
findViewById(R.id.handlerImageView).setVisibility(View.GONE);
}
};
findViewById(R.id.start_timer).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
// Option 1 using timer
myTimer.start();
// Option 2 using handler
myhandler.postDelayed(runnable, COUNT_DOWN_TIME);
}
});
findViewById(R.id.stop_timer).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Option 1 stop timer
myTimer.cancel();
// Option 2 stop handler
myhandler.removeCallbacks(runnable);
}
});
}
}

how to delay put on button click android

public class MainActivity extends Activity implements NetworkMonitorListener {
double _mylat = 0;
double _mylong = 0;
TextView textView1;
Button clcikbutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
clcikbutton = (Button) findViewById(R.id.button1);
clcikbutton.setEnabled(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
clcikbutton.setEnabled(true);
}
});
}
}, 5000));
clcikbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"MM/dd/yyyy hh:mm:ss aa");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
textView1.setText(DateFormat.getDateTimeInstance().format(
new java.util.Date("11/7/2014 5:19:11 AM UTC")));
}
});
}
}
this is my code for delay on button click.I am trying to implement that when i click on the button and after that it should disable for 5 seconds and then it should work.Please help me where i am doing wrong because there is Error coming .
Try to use Handler to disable button for given time :
clcikbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
textView1.setText(DateFormat.getDateTimeInstance().format(new java.util.Date("11/7/2014 5:19:11 AM UTC")));
clcikbutton.setEnabled(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
clcikbutton.setEnabled(true);
}
},5000);
}
});
why not this:
clcikbutton = (Button) findViewById(R.id.button1);
clcikbutton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
clcikbutton.setEnabled(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
clcikbutton.setEnabled(true);
}
}, 5000));
}
});
There are two closing bracket after 5000 please check that.
Try like adding Some period 1000.
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
clcikbutton.setEnabled(true);
}
});
}
}, 5000, 1000);
You can use Handler to execute the line of code after some delay :
clickbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 5s = 5000ms
clickbutton.setEnabled(true);
}
}, 5000);
}
});
Hope it will help you ツ
Timer is flaky, consider using Handler's postDelay() method. Try this:
clcikbutton = (Button) findViewById(R.id.button1);
clcikbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Do what you need to do..
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"MM/dd/yyyy hh:mm:ss aa");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
textView1.setText(DateFormat.getDateTimeInstance().format(
new java.util.Date("11/7/2014 5:19:11 AM UTC")));
// Set the button not-clickable..
clcikbutton.setEnabled(false);
// Then re-enable it after 5 seconds..
final Runnable enableButton = new Runnable() {
#Override
public void run() {
clcikbutton.setEnabled(true);
}
};
new Handler().postDelayed(enableButton, 5000);
}
});
Those code should get you what you want: It will make the button clickable at first, then disable it for 5 seconds the time you click it.
Hope this helped. :)
This is how you do it in Kotlin:
lifecycleScope.launch {
buttonTimer.isEnabled = false
delay(400) // debounce effect
buttonTimer.isEnabled = true
}

android - Thread.sleep causes lags in app

I want to do app to show 3 elements (each 2 seconds) and each start showing after the before element. Here is code:
public class Remember extends Activity
{
TextView text;
ImageView element1, element2, element3, element4 ,element5, element6;
Button button1, button2, button3, button4, button5, button6;
int data, id;
Random random;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remember);
random = new Random();
id=1;
text = (TextView)findViewById(R.id.text);
element1 = (ImageView)findViewById(R.id.element1);
element2 = (ImageView)findViewById(R.id.element2);
element3 = (ImageView)findViewById(R.id.element3);
element4 = (ImageView)findViewById(R.id.element4);
element5 = (ImageView)findViewById(R.id.element5);
element6 = (ImageView)findViewById(R.id.element6);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button5 = (Button) findViewById(R.id.button5);
button6 = (Button) findViewById(R.id.button6);
element1.setVisibility(View.GONE);
element2.setVisibility(View.GONE);
element3.setVisibility(View.GONE);
element4.setVisibility(View.GONE);
element5.setVisibility(View.GONE);
element6.setVisibility(View.GONE);
data = random.nextInt(6)+1;
}
public void button1(View v)
{
gameStart();
}
public void gameStart()
{
do{
if (data==1)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element1.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element1.setVisibility(View.GONE);
}
}.start();
}
else if (data==2)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element2.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element2.setVisibility(View.GONE);
}
}.start();
}
else if (data==3)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element3.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element3.setVisibility(View.GONE);
}
}.start();
}
else if (data==4)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element4.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element4.setVisibility(View.GONE);
}
}.start();
}
else if (data==5)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element5.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element5.setVisibility(View.GONE);
}
}.start();
}
else if (data==6)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element6.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element6.setVisibility(View.GONE);
}
}.start();
}
id=id+1;
text.setText("cos " + id);
data = random.nextInt(6)+1;
try
{
Thread.sleep(2000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}while(id<=3);
}
}
But if I clicked start application start lagging and everything go to norm after time which all elements should be hide. If I delete Thread.sleep all elements show in the same time. What should I do?
Thread.sleep(2000); on the ui thread blocks the ui thread. You should never block the ui thread. Remove the sleep.
To create a delay use a Handler.
Read
http://developer.android.com/guide/components/processes-and-threads.html

How to put countdown timer

i have a question game that has time limit. how can i code if else= if he answer it correct he will intent to the next level and if he didnt answer it within 10sec he will be intent in another class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easyone);
a1 = (Button) findViewById(R.id.btn_ea1);
b1 = (Button) findViewById(R.id.btn_eb1);
c1 = (Button) findViewById(R.id.btn_ec1);
a1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"CORRECT!",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),EasyTwo.class);
startActivity(intent);
}
});
}
}
*\
new CountDownTimer(3000, 100) {
public void onFinish() {
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();

How do I stop a timer that hasn't finished and then start a new one?

I'm attempting to do a guessing game, of sorts. The issue is my timer bleeds into the next one after a question is answered (button pressed) and a new timer starts. This leads to two timers changing a textview at different intervals, which is not how it's supposed to be. I'd like to know how to stop my previous countdown and start a new one. Thanks! Here's my code:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final TextView textic = (TextView) findViewById(R.id.button1);
long total = 30000;
final CountDownTimer Count = new CountDownTimer(total, 1000) {
public void onTick(long millisUntilFinished) {
textic.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText("OUT OF TIME!");
finish();
}
};
Count.start();
Heven't tested the code but I would use something like this:
final TextView textic = (TextView) findViewById(R.id.button1);
final android.os.CountDownTimer Count = new android.os.CountDownTimer(total, 1000) {
public void onTick(long millisUntilFinished) {
textic.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText("OUT OF TIME!");
}
};
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Count.cancel();
Count.start();
}
});
finish CountDownTimer in On finish
#Override
public void onFinish() {
Log.v(TAG, "On Finish");
textvieew.setText("your text");
countDownTimer.cancel();
}

Categories

Resources