Why is not my handler executing? - java

I have the following code:
int x=0;
private void startTimerThread() {
System.out.println("enter");
System.out.println("percentage"+percentage);
System.out.println("x"+x);
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
for (x = 0; x>= percentage; x++ ) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable(){
public void run() {
textpercentage.animate(x, x++);
System.out.println("enter"+x);
}
});
}
}
};
new Thread(runnable).start();
}
I am trying to animate digits on a textview using timely text view, however when I call startTimerThread from my code which is outside of onCreate neither do I get the text view to display not does the system.out execute. What do I miss here?

try like this
Handler handler = new Handler();
int delay=1000;
Runnable rann=new Runnable() {
#Override
public void run() {
//Write Your logic here which you want to perform periodically
System.out.println("Handler is running : ");
//to call the same thread repeatedly calling handler again
handler.postDelayed(rann, delay);
}
};
private void startHandler() {
//here the handler will executes the rannable after that particulary delay milli seconds
handler.postDelayed(rann, delay);
}
private void stopHandler() {
handler.removeCallbacks(rann);
}

Related

delay inside while loop not working

i'm trying to make a delay inside while loop using Thread.sleep() method . here is my code :
new Thread(new Runnable() {
#Override
public void run() {
z=0;
while (z<45){
z++;
handler.post(new Runnable() {
#Override
public void run() {
time.setText(Integer.toString(45-z));
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
this code was working and suddenly a problem occurred . it started to make a delay less than one minute , sumtimes 500 ms and sumtimes less than that
Instead if using a different thread, Thread.sleep(), Handler and while loop you can try only with Handler like this,
private int timerCount = 0;
private static Handler myHandler = new Handler();
private void runVVRunnable() {
myHandler.postDelayed(runnable, 1000);
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
timerCount++;
if ((time == null)) {
return;
}
if (timerCount <= 45) {
time.setText(Integer.toString(timerCount));
runVVRunnable();
}
}
};
#Override
protected void onDestroy() {
super.onDestroy();
myHandler.removeCallbacks(runnable);
}
you can just call runVVRunnable() it will do the same process which you are doing while loop
Just a guess but when sleeping/waiting on Java thread you need to try-catch InterruptedException.
This exception is thrown when "someone" calls interrupt() on your thread.
This will cause the thread to wake up from sleep early than expected.
Check if you catch InterruptedException before your thread terminated.

Threads running at specific time intervals for a specific time in JAVA

I want to use the below mentioned operations in JAVA for android development.
For 30 Seconds ,Run a Function F1() every 1 second (resulting in 30 F1 calls).
Run a Thread t1 forever
The above steps should execute sequentially.
I Have tried with ExecutorServicebut with no success.
This is my code for reference
final Handler h = new Handler();
final int delay = 1000; //milliseconds
ExecutorService executor = Executors.newFixedThreadPool(1);
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
F1();
}
});
for(int i=0;i<30;i++){
executor.submit(t1);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
executor.shutdown();
//Step 2 (THe Second Thread)
h.postDelayed(new Runnable() {
public void run() {
AnotherFunction()
h.postDelayed(this, delay);
}
}, delay);
Generally, ExecutorService is more preferable for such operations. Here is a good post describing the differences and features of Timer and ExecutorService.
As for your question directly - it can be implemented in such way:
// here are Runnables with test logic
Runnable foo = new Runnable() {
#Override
public void run() {
Log.d(">>>", "foo");
onTaskFinished();
}
};
Runnable longRunning = new Runnable() {
#Override
public void run() {
try {
Log.d(">>>", "longRunning started");
Thread.sleep(5000);
Log.d(">>>", "longRunning finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
// and here is valuable logic
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> schedulerHandler;
volatile AtomicInteger tasksNum = new AtomicInteger(0);
private synchronized void onTaskFinished(){
if(tasksNum.incrementAndGet() >= 30){
scheduler.execute(new Runnable() {
#Override
public void run() {
schedulerHandler.cancel(true);
}
});
scheduler.execute(longRunning);
}
}
And then to start operation just invoke this command:
schedulerHandler = scheduler.scheduleAtFixedRate(foo, 0, 1, TimeUnit.SECONDS);
You may consider using the java.util.Timer and java.util.TimerTask classes
If you're doing what I think you're doing you can do as #erosb hinted, use Timer and TimerTask to schedule method executions at a fixed rate.
The following should work for you.
final int DELAY_BEFORE_START = 0;
final int RATE = 1000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
F1();
}
}, DELAY_BEFORE_START, RATE);

I need to stop thread when progress bar reaches 0 in android

I need stop thread and handler when my progress bar reaches 0 from 100 when thread runs the progress bar reaches but the progressStatus value going in negative please help me to stop thread after progress bar reaches 0
new Thread(runn =new Runnable() {
public void run() {
while (progressStatus <= 100) {
progressStatus += doWork();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
handler.post(runn1=new Runnable() {
public void run() {
bar.setProgress(progressStatus);
i=-1;
if(bar.getProgress()==0)
{
handler.removeCallbacks(runn);
handler.removeCallbacks(runn1);
System.out.println("Reached");
congrats.setVisibility(View.VISIBLE);
restart.setVisibility(View.VISIBLE);
rightbutton.setVisibility(View.GONE);
wrongbutton.setVisibility(View.GONE);
}
}
});
}
}
private int doWork() {
return i;
}
}).start();
your program is not thread safe, you actually reading and writing a variable (progressStatus) from two different threads, you must avoid doing that or if you want to do that you must use synchronized block. In order to solve your problem you can do this way:
Thread t;
progressStatus = 100;
t = new Thread(runn =new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
// Update the progress bar
handler.post(runn1=new Runnable() {
public void run() {
bar.setProgress(progressStatus);
progressStatus=progressStatus-1;
if(bar.getProgress()==0)
{
handler.removeCallbacks(runn);
handler.removeCallbacks(runn1);
System.out.println("Reached");
congrats.setVisibility(View.VISIBLE);
restart.setVisibility(View.VISIBLE);
rightbutton.setVisibility(View.GONE);
wrongbutton.setVisibility(View.GONE);
t.interrupt();
}
}
});
another way that i recommend you is using ScheduledThreadPoolExecutor with the function scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit). something like:
final ScheduledThreadPoolExecutor myTimer = new ScheduledThreadPoolExecutor(1);
myTimer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable(){
#Override
public void run(){
}
});
}
}
}, 0,10, TimeUnit.MILLISECONDS);
and in order to close it use myTimer.shutdownNow();

Thread in android not working as expected

I am following a guide that shows how to create a Pong game. There is a part, where I am supposed to create a Thread, and call a function that moves the ball.
This is the code I created:
package com.ozadari.pingpong;
public class PingPongGame extends Thread {
private Ball gameBall;
private PingPongView gameView;
public PingPongGame(Ball theBall,PingPongView mainView)
{
this.gameBall = theBall;
this.gameView = mainView;
}
#Override
public void run()
{
while(true)
{
this.gameBall.moveBall();
this.gameView.postInvalidate();
try
{
PingPongGame.sleep(5);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}}
The thread is called and working, but it doesn't print anything. I tried to cancel the infinte loop and make the loop run 100 times. After I wait a while, it prints to the screen as it should be after 100 runs, but it doesn't print anything in the middle.
What is the problem? How can I fix it?
Unsure from the code you've posted but anyway, you can use a handler and have it run once every second like so (change the time to what you want):
Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
//do your stuff here
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
http://developer.android.com/reference/android/os/Handler.html
You can also use a normal thread, and call start at the end.
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(1000);
handler.post(r);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();

Android -Timer concept

Sorry for asking such a basic question, Actually i need to call a method after certain time interval which is actually assigning a text to textView in android,which is supposed to change.So please suggest me the best way to do this.
Thanking you in anticipation.
{
int splashTime=3000;
int waited = 0;
while(waited < splashTime)
{
try {
ds.open();
String quotes=ds.getRandomQuote();
textView.setText(quotes);
ds.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
waited+=100;
}
Have you considered CountDownTimer ? For example something like this:
/**
* Anonymous inner class for CountdownTimer
*/
new CountDownTimer(3000, 1000) { // Convenient timing object that can do certain actions on each tick
/**
* Handler of each tick.
* #param millisUntilFinished - millisecs until the end
*/
#Override
public void onTick(long millisUntilFinished) {
// Currently not needed
}
/**
* Listener for CountDownTimer when done.
*/
#Override
public void onFinish() {
ds.open();
String quotes=ds.getRandomQuote();
textView.setText(quotes);
ds.close();
}
}.start();
Of course, you can put it in a loop.
you can use Timer to update your UI with delay like this:
long delayInMillis = 3000; // 3s
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
// you need to update UI on UIThread
runOnUiThread(new Runnable() {
#Override
public void run() {
ds.open();
String quotes=ds.getRandomQuote();
textView.setText(quotes);
ds.close();
}
});
}
}, delayInMillis);
Use a handler and put it in a Runnable:
int splashTime = 3000;
Handler handler = new Handler(activity.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
ds.open();
String quotes=ds.getRandomQuote();
textView.setText(quotes);
ds.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}, splashTime);

Categories