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);
Related
Hi my app needs a realtime data from database and I'm posting it on my TextView and I can't update the TextView as the database updates. I tried using Timer but its still the same.
Here is my code,
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
timer.schedule(timerTask, 0, 5000);
}
private void stopTimerTask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
final AcceptCars Cars = (AcceptCars) getIntent().getSerializableExtra("cars");
renterLat.setText(Cars.renterLat);
renterLng.setText(Cars.renterLng);
Log.d(TAG,renterLat.getText().toString());
Log.d(TAG,renterLng.getText().toString());
}
});
}
};
}
And here is where I get the Cars.renterLat and Cars.renterLng,
public class AcceptCars implements Serializable {
#SerializedName("renterLat")
public String renterLat;
#SerializedName("renterLng")
public String renterLng;
}
This is the logic you should be following. I used a Handler instead of a Timer. Inside the run method you need to call your webservice and get the updated value from the db. Use runOnUiThread to update the value to the UI from a Thread.
See the code below,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Handler taskHandler = new Handler();
taskHandler.postDelayed(myTask, 0);
}
private Runnable myTask = new Runnable(){
public void run() {
queryDb();
// repeat the task
taskHandler.postDelayed(this, 1000);
}
};
private void queryDb(){
new Thread(new Runnable() {
#Override
public void run() {
// call you webservice
String data = callWebservice();
// parse the data in to AcceptCars pojo class
AcceptCars Cars = parseData(data);
//update the UI
runOnUiThread(new Runnable() {
#Override
public void run() {
renterLat.setText(Cars.renterLat);
renterLng.setText(Cars.renterLng);
}
});
}
}).start();
}
You can even use countdown timer.
Here is the link https://developer.android.com/reference/android/os/CountDownTimer.html
TimerTasks are really hard to deal with IMO. You should use a Handler and call postDelayed to do something after a certain amount of time.
Alternatively, you can try out this timer class I wrote:
import android.os.Handler;
public class Timer {
private Handler handler;
private boolean paused;
private int interval;
private Runnable task = new Runnable () {
#Override
public void run() {
if (!paused) {
runnable.run ();
Timer.this.handler.postDelayed (this, interval);
}
}
};
private Runnable runnable;
public int getInterval() {
return interval;
}
public void setInterval(int interval) {
this.interval = interval;
}
public void startTimer () {
paused = false;
handler.postDelayed (task, interval);
}
public void stopTimer () {
paused = true;
}
public Timer (Runnable runnable, int interval, boolean started) {
handler = new Handler ();
this.runnable = runnable;
this.interval = interval;
if (started)
startTimer ();
}
}
It is really simple to use.
You can use it like this:
Timer timer = new Timer(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
final AcceptCars Cars = (AcceptCars) getIntent().getSerializableExtra("cars");
renterLat.setText(Cars.renterLat);
renterLng.setText(Cars.renterLng);
Log.d(TAG,renterLat.getText().toString());
Log.d(TAG,renterLng.getText().toString());
}
}
}
}, 5000, true);
I have created this class, but there is an error last part saying
"Syntax error on token "(", delete this token" on the "timers.schedule part"
public class refrend
{
Timer timers = new Timer();
final Handler handler = new Handler();
int initial = 1000;
int looper = 6000;
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
new activityIns().execute();
}
});
}
};
timers.schedule(task, initial, looper);
}
Thanks for your help :)
what you can do is to create a function
public class refrend {
Timer timers = new Timer();
final Handler handler = new Handler();
int initial = 1000;
int looper = 6000;
public void your_Function(){
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
// new activityIns().execute();
}
});
}
};
timers.schedule(task, initial, looper);
}
}
now you can call that function in you class by your_Functino();
and if you want to use that function out side of class create it object and call
it
refrend object=new refrend();
object.your_Function();
I need to send one command to the server from an android activity at regular intervals of time and then receive the output and display it on the Layout of the activity.
How can I achieve the above task?
I think this is the sort of thing you're looking for:
public void myAsynchronousTask() {
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 {
BackgroundTask backgroundTask = new BackgroundTask();
// The above is the class that performs your task
backgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 50000); //this runs every 5 seconds. Feel free to change it
}
Change it according to your needs.
In the above case for each and every time one async task object will be created but in this case objects will not be created multiple times and with out completing first request the send request will be started...
private void startFectchingTheData() {
asynT.execute();
}
Runnable rannable = new Runnable() {
#Override
public void run() {
asynT.execute();
}
};
Handler handler = new Handler();
AsyncTask<Void, Void, Void> asynT = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Write the fetching logic here
return null;
}
protected void onPostExecute(Void result) {
int interval = 5000;
handler.postDelayed(rannable, interval);
};
};
protected void onDestroy() {
handler.removeCallbacks(rannable);
};
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 <--------------------
}
})
}
});
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);
}
});
}
}