Despite thorough search of other user's questions, I don't seem to understand how to do a countdown timer. All I wanna do is setting visibility to GONE after 30 seconds without touching the screen. So far I've done this:
public class StatusFragment extends Fragment {
CountDownTimer countDownTimer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//SET VISIBILITY TO VISIBLE
}
public void onFinish() {
//SET VISIBILITY TO GONE
}
}.start();
cpHover.setOnClickListener(new OnClickListener() {
//Should I countDownTimer.start()? It says there's an error
#Override
public void onClick(View view) {
if(textBox.getVisibility()==View.GONE){
donutProgress.setVisibility(View.VISIBLE);
textBox.setVisibility(View.VISIBLE);
image.setVisibility(View.VISIBLE);
}
else if(textBox.getVisibility()==View.VISIBLE){
donutProgress.setVisibility(View.GONE);
textBox.setVisibility(View.GONE);
image.setVisibility(View.GONE);
}
}
});
The process should be quite easy. Setting in onCreate() a 30-second countdown that starts every time the user clicks cpHover. When they click it again, it should restart the countdown. There are two ways of hiding the UI: clicking on the screen when it's visible or not clicking at all in 30+ seconds.
Thanks in advance.
add this inside your onCreate()
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//set visibility as gone here
if(textBox.getVisibility()==View.VISIBLE){
donutProgress.setVisibility(View.GONE);
textBox.setVisibility(View.GONE);
image.setVisibility(View.GONE);
}
}
}, 30000);
Its very Simple, just change your code as per below :
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//SET VISIBILITY TO VISIBLE
donutProgress.setVisibility(View.VISIBLE);
textBox.setVisibility(View.VISIBLE);
image.setVisibility(View. VISIBLE);
}
public void onFinish() {
//SET VISIBILITY TO GONE
donutProgress.setVisibility(View.GONE);
textBox.setVisibility(View.GONE);
image.setVisibility(View.GONE);
}
}
}.start();
you want to start CountDownTimer in Click event then add above code in the click event
Happy Coading....
Update your code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setUpCountDown();
cpHover.setOnClickListener(new OnClickListener() {
//Should I countDownTimer.start()? It says there's an error
#Override
public void onClick(View view) {
if(countDownTimer != null) {
countDownTimer.cancel();
}
setUpCountDown();
}
);
}
private void setUpCountDown() {
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//SET VISIBILITY TO VISIBLE
donutProgress.setVisibility(View.VISIBLE);
textBox.setVisibility(View.VISIBLE);
image.setVisibility(View.VISIBLE);
}
public void onFinish() {
donutProgress.setVisibility(View.GONE);
textBox.setVisibility(View.GONE);
image.setVisibility(View.GONE);
}
}.start();
}
Related
I am new to android studio and want to overcome from this problem.
It gonna help me a lot while creating some future apps like , stopwatch, timer etc etc.
Thanks in advance !!
public class MainActivity extends AppCompatActivity {
private EditText k;
private Button start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
k=findViewById(R.id.kf);
start=findViewById(R.id.startf);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i=1;i<1000;i++)
{
k.setText(String.valueOf(i) );
}
}
});
}
}
As #f1sh already mentioned in the comments your for loop is executing at such a speed that all you see is the final value. For such cases in android one of the best solutions is to make use of Handler for posting delayed functions without blocking the UI.
So for showing 1 to 999 you can try something like this:
public class MainActivity extends AppCompatActivity {
private EditText k;
private Button start;
int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
k=findViewById(R.id.kf);
start=findViewById(R.id.startf);
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
public void run() {
if (count < 1000) {
k.setText(String.valueOf(count));
count++;
handler.postDelayed(this, 1000);
} else {
handler.removeCallbacks(this);
}
}
};
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count = 1;
handler.postDelayed(runnable, 0);
}
});
}
}
this will keep changing the text in TextView with a 1 second delay, you can change the delay as needed by setting the milliseconds in runnable.
You can even use a countdown timer for this purpose but its more like a workaround and requires you to calculate the correct time etc.
For example displaying 1 to 10 would be something like this:
...
count = 1;
new CountDownTimer(11000, 1000) {
public void onTick(long millisUntilFinished) {
tv.setText(String.valueOf(count));
count++;
}
public void onFinish() {
}
}.start();
here you are displaying the value every 1 second for 11 seconds
I have a function that has a timer that I want to "restart" every time you click the button. I tried doing this but when the button is clicked several times it appears that there are several timers still going on when I only want the one. How do I fix this?
So, onClick => Cancel last timer => Start new timer
public void startService(android.view.View view) {
final SharedPreferences sP = getSharedPreferences("com.example.safetyNet", MODE_PRIVATE);
final Button button = findViewById(R.id.button3);
final Intent transIntent = new Intent(this, CheckPinActivity.class);
CountDownTimer cdt = new CountDownTimer(sP.getInt("TiT", 10) * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
button.setText(String.valueOf(millisUntilFinished).substring(0,2));
}
#Override
public void onFinish() {
if(sP.getBoolean("lockedDown", false) == true){
startActivity(transIntent);
}
}
};
cdt.cancel();
cdt.start();
}
The problem is that, everytime you call the method "startService(android.view.View view) {}", a new CountDownTimer is created, so the previous CountDownTimer that you created is not the same reference as this one.
To solve that, you are going to have to create the CountDownTimer as a class member for your class:
public YourClass {
private CountDownTimer cdt;
.... (do whatever)....
public void startService(android.view.View view) {
final SharedPreferences sP = getSharedPreferences("com.example.safetyNet", MODE_PRIVATE);
final Button button = findViewById(R.id.button3);
final Intent transIntent = new Intent(this, CheckPinActivity.class);
if (cdt == null) {
cdt = new CountDownTimer(sP.getInt("TiT", 10) * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
button.setText(String.valueOf(millisUntilFinished).substring(0,2));
}
#Override
public void onFinish() {
if(sP.getBoolean("lockedDown", false) == true){
startActivity(transIntent);
}
}
};
} else {
cdt.cancel();
}
cdt.start();
}
Hope that helps you
Hi i am trying to cancel a countdown timer in On-tick function, It is working fine in lollipop but not working in Kitkat and below. How cancel it from a OnTick() function.
private void startTimer(final int minuti) {
countDownTimer = new CountDownTimer(60 * minuti * 1000 + sec * 1000,
500) {
#Override
public void onTick(long leftTimeInMilliseconds) {
CountDownTimer.cancel();
}
#Override
public void onFinish() {
}
}.start();
}
Somehow if you call countdowntimer.cancel of a CountDownTimer object in its own onTick method it won't work!
The simplest way to solve your problem is defining another CountDownTimer, same as the main one, in order to check the condition to call countdowntimer.cancel. The point is that you are calling objects cancel method from outside of its own onTick method.
Check the example below:
CountDownTimer countdowntimer;
CountDownTimer assist;
long millisuntillfinish = 10000;
int interval = 100;
countdowntimer = new CountDownTimer(millisuntillfinish, interval) {
#Override
public void onTick(long millisUntilFinished) {
// if(true) countdowntimer.cancel(); (doesnt work)
}
#Override
public void onFinish() {
}
};
assist = new CountDownTimer(timertillfinish, timerinterval) {
#Override
public void onTick(long millisUntilFinished) {
if (true) {
countdowntimer.cancel();
}
}
#Override
public void onFinish() {
assist.cancel();
}
};
I know this question is more than 6 years old, but calling super.cancel(); within onTick() did the trick for me.
Leaving this here for the next unfortunate soul looking for an answer to this question.
ie.
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
if(someCondition)
super.cancel();
}
public void onFinish() {
//do something else
}
}.start();
new CountDownTimer(time, 1000) {
public void onTick(long millisUntilFinished) {
if (((millisUntilFinished/1000)%5)==0){ //every 5 sec
if(true)
{
this.cancel();
}
}
}
public void onFinish() {
//do somethhing
}
}.start();
I have been looking around and I have found this post where they call to the cancel() method in the onTick() using an alternative to the Android countDownTimer.
I had also this problem, and I created a global variable of a countDownTimer and I called to the cancel method in the activity when I needed, like myCountDownTimer.cancel().
private CountDownTimer mCountDownTimer;
private CountDownTimer createTimer(){
return new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//do what you want
}
public void onFinish() {
//do what you want
}
}.start();
}
In your activity call:
mCountDownTimer = this.createTimer();
And if you want to cancel it:
mCountDownTimer.cancel();
I have my Java code, I have this layout where there is a ImageView and a Button, in my Drawable folders I have to images, What I want is: When the Button advance is Clicked, the ImageView will show the image(image1.png that is in the drawable folder) and the after 5 seconds show the other image(image2.png). The problem is that I don't know how to make that pause.
advance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image.setImageResource(R.drawable.image1);
//TO WAIT 5 SCONDS...
image.setImageResource(R.drawable.image2);
}
});
Use the default CountDownTimer
http://developer.android.com/reference/android/os/CountDownTimer.html
Set the first image
Start the CountDownTimer
set the new image in onFinish()
new CountDownTimer(5000, 1000) { // 5000 = 5 sec
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
image.setImageResource(R.drawable.image2);
}
}.start();
Edit:
extra info: in the documentation, you can find
CountDownTimer(long millisInFuture, long countDownInterval)
so the first parameter is the total time you want to have (in milliseconds, 5 sec = 5000 milis) and the second parameter is the interval. Here it's 1000 = 1 sec. This means that the timer will tick every second. So the onTick(long ) will be called every second (when the timer is running)
You can also use a Timer and TimerTask
advance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image.setImageResource(R.drawable.image1);
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
image.setImageResource(R.drawable.image2);
}
}, 5000);
}
});
You can also use a Handler: http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long)
advance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image.setImageResource(R.drawable.image1);
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.image2);
}
}, 5000);
}
});
public class MainActivity extends Activity
{
int min, sec;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
min = 5;
sec = 0;
final TextView timer1 = (TextView) findViewById(R.id.timer1);
timer1.setText(min + ":" + sec);
Thread t = new Thread() {
public void run() {
sec-=1;
if (sec<0) {
min-=1;
sec=59;
}
timer1.setText(min + ":" + sec);
try
{
sleep(1000);
}
catch (InterruptedException e)
{}
}
};
t.start();
}
}
This is a code for a Thread in Java but it doesn't work. Can you help me?
Its a Timer that counts down from 5 Minutes to 0:00.
In your case you are using threads. So you cannot update ui from the thread other than the ui thread. SO you use runOnUithread. I would suggest you to use a countdown timer or a Handler.
1.CountDownTimer
http://developer.android.com/reference/android/os/CountDownTimer.html
Here's a link to another example. Suggest you to check the link for the count down timer.
Countdowntimer in minutes and seconds
Example:
public class MainActivity extends Activity {
Button b;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startTimer(200000);
}
});
}
private void startTimer(long time){
CountDownTimer counter = new CountDownTimer(30000, 1000){
public void onTick(long millisUntilDone){
Log.d("counter_label", "Counter text should be changed");
tv.setText("You have " + millisUntilDone + "ms");
}
public void onFinish() {
tv.setText("DONE!");
}
}.start();
}
}
2.You can use a Handler
Example :
Handler m_handler;
Runnable m_handlerTask ;
int timeleft=100;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
if(timeleft>=0)
{
// do stuff
Log.i("timeleft",""+timeleft);
timeleft--;
}
else
{
m_handler.removeCallbacks(m_handlerTask); // cancel run
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
3.Timer
Timer runs on a different thread. You should update ui on the ui thread. use runOnUiThread
Example :
int timeleft=100;
Timer _t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
Log.i("timeleft",""+timeleft);
//update ui
}
});
if(timeleft>==0)
{
timeleft--;
}
else
{
_t.cancel();
}
}
}, 1000, 1000 );
You are trying to update the UI Thread from a background Thread with
timer1.setText(
which you can't do. You need to use runOnUiThread(), AsyncTask, CountDownTimer, or something similar.
See this answer for an example of runOnUiThread()
But CountDownTimer is nice for things like this.
Also, when posting a question on SO, statements like "it doesn't work." are very vague and often unhelpful. Please indicate the expected results compared to actual results of your code and logcat if the app is crashing.