AsyncTask not called from TimerTask android - android

I am developing the project which continuously get datas from server at 30secs interval.So I used Handler with Timer and called Asynctask.
But my asynctask not called.This is my code,
final Handler handler;
handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask()
{
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try
{
System.out.println("I am xxx");
LiveTrack myActivity = new LiveTrack();
AsyncTask<String, String, String> task = myActivity.new VehiclePath();
task.execute();
}
catch (Exception e)
{
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 30000);
Can anyone guide me why I am facing this?

You cannot create an AsyncTask from within a TimerTask because it runs on a spawned thread, i.e.
not the UI thread).
AsynTasks must be created and execute()-ed only on the UI thread.
Instead, use an Executor for the background processing and call runOnUiThread when it is time to update the UI.
ExecutorService executorPool = Executors.newSingleThreadExecutor();
executorPool.execute(new Runnable() {
public void run() {
// do background processing here <------------------
myActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// update ui here <--------------------
}
})
}
});

Related

Timer task implementing handler

UPDATE : The code is working only that I dint init the textview, but this question is answered so I cant remove it either. So I will leave this question as it is for anyone trying to implement a Timertask with handler that makes use of Looper.getMainLooper that directly attaches it to the UI THREAD.
OLD QUERY :Hello guys I am trying to implement a timer that runs a task which has a handler.
I am using it to update the UI every second.
This is what I am implementing:
private void setRepeatingAsyncTask() {
handler = new Handler(Looper.getMainLooper());
timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
i++;
tview.setText(String.valueOf(i));
} catch (Exception e) {
// error, do something
}
}
});
}
};
timer.schedule(task, 0, 1000); // interval of one minute
}
when I make setRepeatingAsyncTask() on create or somewhere else like button clicklistner, etc either the timer or the handler is not starting.
Please help new to android!
I used Handler to process the task every 1 sec, Using just Handler:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//some task
handler.postDelayed(this, 1000); //looping is every 1 secs
}
}, 0); //initial delay of 0

Displaying a stopwatch in an android app in a textView

I have setup a stop watch using the com.apache.commons library and the stop watch seems to work fine. What I don't know how to do is display this stopwatch in a textView in my app. In general, I have no idea how that would work, i.e. How exactly would a stopwatch be displayed in a textView, given that the time on a stopwatch keeps changing constantly? At the moment, I have the code below and it updated the text in the textView every second for about 2 seconds and then I got a weird error. I'm not even sure if this is the right way to go about doing this. Please help!
Timer timer = new Timer();
TimerTask timerTask;
timerTask = new TimerTask() {
#Override
public void run() {
timeText.setText(time.toString());
}
};
timer.schedule(timerTask, 0, 1000);
The error I got after 2 seconds (and it successfully updated the time) was :
"only the original thread that created a view hierarchy can touch its views"
You can only update a TextView on the UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
//stuff that updates ui
}
});
Your code becomes
Timer timer = new Timer();
TimerTask timerTask;
timerTask = new TimerTask()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
timeText.setText(time.toString());
}
});
}
};
timer.schedule(timerTask, 0, 1000);
You may have to do myActivityObject.runOnUiThread() if you're getting an error there.
See this for more detail.
To update a view from another thread, you should use handler.
private void startTimerThread() {
Handler handler = new Handler();
Runnable runnable = new Runnable() {
private long startTime = System.currentTimeMillis();
public void run() {
//Change the condition for while loop depending on your program logic
while (true) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable(){
public void run() {
timeText.setText(time.toString());
}
});
}
}
};
new Thread(runnable).start();
}

Android time delay

How to make a delay that could call a function after some time but the thread still should be running. Is there any better way than this.
new Thread(new Runnable() {
public void run(){
try{ Thread.sleep(recordtime); }
catch(Exception e){}
runOnUiThread(new Runnable() {
#Override
public void run() {
reset();
}
});
}
}).start();
To run some code on Ui thread , after some delay:
Handler h = new Handler(Looper.getMainLooper());
Runnable r = new Runnable() {
#Override
public void run() {
//--code run in Main, UI thread
}
};
h.postDelayed(r,2000); //-- run after 2 seconds
Handler require a Looper on target thread. UI thread already has it, other threads need to be configured first.
Other options are:
Timer:
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
//--code run in separate thread
}
},2000);
And ScheduledExecutorService:
ScheduledExecutorService se = Executors.newSingleThreadScheduledExecutor();
se.schedule(new Runnable() {
#Override
public void run() {
//--code run in separate thread
}
},2, TimeUnit.SECONDS);

update data to server in the background android

How to update data to server ? I have used the code below but its not executing after 10 mins.
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(new Runnable(){
public void run() {
//update data to server
}
}, 0, 600, TimeUnit.SECONDS);
You must use your own Thread.
Here is solution using AsyncTask....
All code put in your Activity class.
public void toCallAsynchronous() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
MyAsyncTask task = new MyAsyncTask();
task.execute(txtSearchField.getText().toString());
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 2000); // execute in every 2 second
}
// AsyncTask Class
private class MyAsyncTask extends AsyncTask<String, Object, List<ModelObject>> {
#Override
protected List< ModelObject > doInBackground(String... params) {
// Call web service
return null;
}
#Override
protected void onPostExecute(List< ModelObject > result) {
super.onPostExecute(rezultat);
// Update UI
}
}
Try with this
private static final ScheduledExecutorService worker = Executors
.newSingleThreadScheduledExecutor();
worker.schedule(new Runnable(){
public void run() {
//update data to server
}, 600, TimeUnit.SECONDS);

Start AsyncTask in TimerTask

I have a timer that I want to start an AsyncTask when the countdown is done. If I put the execution of it in a handler it loops it and starts it many times. And if I dont put it in a Handler I get the following crash:
can't create handler inside thread that has not called looper.prepare()
timer.schedule(new ListUpdate(), helper.nextListUpdate.get(0));
class ListUpdate extends TimerTask {
private Handler mHandler = new Handler(Looper.getMainLooper());
public void run() {
mHandler.post(new Runnable() {
public void run() {
AsyncTask<Integer, Void, Boolean> task = new updateList();
task.execute();
}
});
}
}
Any suggestions of how I can solve this?
AsyncTask is supposed to run on UI thread only. In your case, seems like you are not running it properly on a UI thread.
Perhaps try it like this:
timer.schedule(new ListUpdate(), helper.nextListUpdate.get(0));
class ListUpdate extends TimerTask {
Looper looper = Looper.getMainLooper();
looper.prepareMainLooper();
private Handler mHandler = new Handler(looper);
public void run() {
mHandler.post(new Runnable() {
public void run() {
AsyncTask<Integer, Void, Boolean> task = new updateList();
task.execute();
}
});
}
}
By adding a handler outside of the TimerTask which I call from the TimerTask I could make it work!
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
RelativeLayout rl_header = (RelativeLayout)findViewById(R.id.rl_header);
Desktop desktop = helper.getDesktop();
try {
desktop.inflate(ll, rl_header, banners, DesktopApp.this);
Collections.sort(helper.nextListUpdate);
helper.nextListUpdate.remove(0);
timer = new Timer();
if (helper.nextListUpdate.size() > 0) timer.schedule(new ListUpdate(), helper.nextListUpdate.get(0));
} catch (Exception e) {
e.printStackTrace();
}
}
};
class ListUpdate extends TimerTask {
public void run() {
DesktopApp.this.runOnUiThread(new Runnable() {
#Override
public void run() {
handler.sendEmptyMessage(0);
}
});
}
}

Categories

Resources