Error in countdowntimer in android? - java

I am working on a layout which shows a tab like structure on bottom of the layout. Which I need to show on double tap and then hide it after 5 sec. So I am using this countdown timer:
public void timer()
{
cdt=new CountDownTimer(5000,1000) {
#Override
public void onTick(long millisUntilFinished) {
System.out.println("Timer Working"+millisUntilFinished+"");
}
#Override
public void onFinish() {
System.out.println("Finished");
main =(LinearLayout)findViewById(R.id.parent);
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams)main.getLayoutParams();
mlp.height=420;
set_up_views();
find_module();
tl.setVisibility(View.INVISIBLE);
}
}.start();
}
But I dont know how to stop and restart this timer. How can I do?

I suggest you not to Use CountDownTimer for this case.
Use Handler.postDelayed(Runnable runnable, long delay)
public class yourActivity extends Activity
{
public Handler handler = new Handler();
...
public void hideAfter5Sec()
{
handler.postDelayed(new Runnable()
{
View view = findViewById(view_to_hide);
view.setVisibility(View.INVISIBLE);
}, 5000);
}
}
postDelayed will execute that code after 5Sec.
EDITED:
postDelayed will be call only once after 5 Sec through Lopper.loop(). If there are multiple call to hideAfter5Sec() then only you will get multiple call to postDelayed.
If you have multiple call hideAfter5Sec() i dont think there is any wrong because hideAfter5Sec() is just hidding it. so if it one or many your view will be hidden.
If in case you want to hide only in the last call of hideAfter5Sec() use this variant.
public class yourActivity extends Activity
{
public Handler handler = new Handler();
public long lastHideAfter5Sec = 0L;
...
public void hideAfter5Sec()
{
lastHideAfter5Sec = System.currentTimeMillis();
handler.postDelayed(new Runnable()
{
if(System.currentTimeMillis() - lastHideAfter5Sec < 5000)
return;
View view = findViewById(view_to_hide);
view.setVisibility(View.INVISIBLE);
}, 5000);
}

Related

How can i run a button automatically every second until de if condition be true?

I need that a button can run automatically every 1-2 seconds, and, when the if condition (that i have in the method which is used by the button) is fulfilled, this function must be stopped.
I've tried this but it wasn't what i wanted because with this code the button only runs one time:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Consulta.performClick();
}
}, 1000);
onClick of my button:
public void consultaBD(View view)
{
DB db = new DB(getApplicationContext(),null,null,1);
String buscar = text_view.getText().toString();
String[] datos;
datos=db.buscar_reg(buscar.trim());
db.infraccion(buscar.trim());
if(datos[2] =="Encontrado")
{
App.matricula=buscar;
startActivity(new Intent(getApplicationContext(), MatriculasActivity.class));
Toast.makeText(getApplicationContext(),datos[2],Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),datos[2],Toast.LENGTH_SHORT).show();
}
}
Another method would be to use Timers to initiate the button click every x seconds. However, in this answer I'll stick with the method you're using. Your handler appears to be incorrect, try something like this instead:
Replace your handler with:
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
#Override
public void run() {
Consulta.performClick();
handler.postDelayed(this, 1000);
}
};
And initiate it with: (where 1000 is the time (in milliseconds) between each execution)
handler.postDelayed(runnable, 1000);
UPDATE:
You have also requested that the event is fired when the text inside of a textbox is changed. To do this, you need to create a new event listener (make sure you replace field1 with the actual reference to your textbox):
field1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
/* Add the Handler Call here */
handler.postDelayed(runnable, 1000);
}
});
whatever context I understood, here is the raw code which may help you.
Handler handler = new Handler();
//initialize this method once by either clicking on button or as the activity starts
void checkAndPerformClick(boolean conditionFulfilled) {
if (conditionFulfilled) {
handler.removeCallbacksAndMessages(null);
return;
}
handler.postDelayed(new Runnable() {
#Override
public void run() {
Consulta.performClick();
checkAndPerformClick(datosEqualsEncontrado());
}
}, 1000);
}
boolean datosEqualsEncontrado() {
// apply your logic here as the name suggests
return false;
}

How to delay a timer on an activity launch?

I have implemented a simple timer with CountDownTimer on my game and I need it to start ater a few seconds when the activity is started.
On my main activity's onCreate method, I call this:
playingTime();
Which is as follow
public void playingTime() {
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
String elapsedTime = String.valueOf(millisUntilFinished / 1000);
timer.setText(elapsedTime);
}
public void onFinish() {
timer.setText(R.string.timer_game_over_text);
}
}.start();
}
The timer start normally but immediatelly as the activity is launched. I would like to set a delay before it get executed or if there is a better way to set timer in games. (Count down timer and nomal timer)
You can use the handler in onCreate() method as shown below and playingTime will be called after 1 second
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
playingTime();
}
}, 1000);
You can add delay using Handler like as below:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Executed after YOUR_DELAY_IN_MILLIS
playingTime()
}
}, YOUR_DELAY_IN_MILLIS);
Put the code in your activity onCreate() method
You can set a delay like this :
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
// call method here
}
}, MY_DELAY_IN_MS);
Replace MY_DELAY_IN_MS with your own delay

postDelay vs ScheduledThreadPoolExecutor

I'm trying to produce an animation with delay less than 1 milli second.
Based on my research, I found some answers about ScheduledThreadPoolExecutor.
Unfortunately, I applied the following code but it's not working as I expected..
public class MainActivity extends Activity {
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
private Handler mHandler = new Handler();
public void buttonClicked(View v){
if(v.getId() == R.id.start_animation)
{
//Case1
mHandler.post(animateImage);
//Case2
//startEffect();)
}
}
private Runnable animateImage = new Runnable() {
#Override
public void run() {
runOnUiThread(
new Runnable()
{
public void run()
{
doTheAnimation1();
}
});
}
};
private void doTheAnimation1() {
doFlipImage();
}
private void startEffect()
{
long delay = 1000; //the delay between the termination of one execution and the commencement of the next
exec.scheduleAtFixedRate(animateImage, 0, delay, TimeUnit.MICROSECONDS);
}
}
According to the code, once the button is clicked the mHandler will call the animateImage, animateImage will doFlipImage which will create a Bitmap and assign it to the canvas and I start drawing over that canvas, and this bitmap will be used to invalidate an imageview.
if I'm using mHandler then everythings works fine, but if I'm using ScheduledThreadPoolExecutor (so I will call startEffect method instead of mHandler.post), then the imageview appears white after the drawings happened as I guess, How could I solve this issue.

Issue calling a custom view method from runnable

I am using a handler to call runnable after a delay of 5 seconds. this then calls a method in a custom view. the problem im having is that the method is being called but the delay is far greater than 5 seconds.
code is as follows.
final Handler h = new Handler();
h.postDelayed(new Runnable()
{
#Override
public void run()
{
buttonArray.get(1).activate();
}
}, 5000);
and the code in the custom view that is being called
public void activate()
{
active = true;
this.animate().alpha(0.4f).setDuration(150);
}
Thanks

Error in derived TimerTask class: `Can't create handler inside thread that has not called Looper.prepare()`

I want to cyclically update an Android Layout. For this purpose I wrote a short class derived from TimerTask.
Unfortunately my code causes an exception and I do not really know, what the problem might be. :(
So maybe anybody could help.
Thanks
Chris
Here's my code:
In the main activity I've got:
private MyLayoutClass m_MyLayout;
...
public void onCreate(Bundle savedInstanceState)
{
...
m_MyLayout = new AdLayout(this);
Timer caretaker = new Timer();
caretaker.schedule(new MyReloadTimerTask(m_MyLayout), 1000, 5000);
...
}
This is my derived TimerTask class:
public class MyReloadTimerTask extends TimerTask
{
private MyLayoutClass m_MyLayout;
public MyReloadTimerTask(MyLayoutClass aLayout)
{
m_MyLayout = aLayout;
}
#Override
public void run()
{
m_MyLayout.doReload();
}
}
The doReload() cannot be executed, I get an exception with this message: Can't create handler inside thread that has not called Looper.prepare()
Timertask runs on a different thread. So you cannot not update/access ui from a background thread.
Probably m_MyLayout.doReload() is updating ui. Use a Handler or runOnUiThread
runOnUiThread(new Runnable() {
#Override
public void run() {
m_MyLayout.doReload()
}
});
Using Handler
Handler m_handler;
Runnable m_handlerTask ;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
// do something
m_handler.postDelayed(m_handlerTask, 1000);
// repeat some task every 1 second
}
};
m_handlerTask.run();
To cancel the run
m_handler.removeCallbacks(m_handlerTask);

Categories

Resources