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);
Related
My app needs tracking of real time so I need a button that needs to trigger every 5 seconds but I have no idea how to do it. Can you teach me how?
I want that in every 5 seconds that AsyncTask will be triggered.
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap postLoc = new HashMap();
postLoc.put("txtLat", tvLat.getText().toString());
postLoc.put("txtLng", tvLong.getText().toString());
postLoc.put("txtOwner", pref.getString("username","").toString());
PostResponseAsyncTask taskLoc = new PostResponseAsyncTask(getActivity(), postLoc,false, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, tvLat.getText().toString());
Log.d(TAG, tvLong.getText().toString());
Intent i = new Intent(getActivity(),GPS_Service.class);
getActivity().startService(i);
}
});
taskLoc.execute("http://carkila.esy.es/carkila/locationUpdate.php");
}
});
I think this code might be useful to trigger the code every 5 second
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
#Override
public void onCreate() {
super.onCreate();
startTimer();
}
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
timer.schedule(timerTask, 0, 5000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
//code to run after every 5 seconds
}
});
}
};
}
Create a method like this and call the method on button click and also call the method by using a handler like this:
mRunnable = new Runnable() {
public void run() {
public void toBecalled_Every_5_Second();
mHandler.postDelayed(mRunnable, 5000);
}
};
mHandler.postDelayed(mRunnable, 5000);
public void toBecalled_Every_5_Second(){
PostResponseAsyncTask taskLoc = new PostResponseAsyncTask(getActivity(), postLoc,false, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, tvLat.getText().toString());
Log.d(TAG, tvLong.getText().toString());
Intent i = new Intent(getActivity(),GPS_Service.class);
getActivity().startService(i);
}
});
taskLoc.execute("http://carkila.esy.es/carkila/locationUpdate.php");
}
so it will call the method every 5 second and the a sync task will execute....
I would like to have a CountDownTimer which will trigger the button click function after every 5 seconds.
CountDownTimer mTimer = new CountDownTimer(50000, 1000) {
public void onTick(long millisUntilFinished) {
// Do nothing
}
public void onFinish() {
btnStart.performClick();
this.start(); // Restart
}
}.start();
You can use Timer with TimerTask and Handler to update the result to main thread i.e your UI.
Something like this:
Timer timer;
TimerTask timerTask;
//we are going to use a handler to be able to run in our TimerTask
final Handler handler = new Handler();
private void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run process
handler.post(new Runnable() {
public void run() {
/**************************/
/** Do your process here **/
/**************************/
}
});
}
};
}
private void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, start run TimerTask then run every 5000ms i.e 5 seconds.
timer.schedule(timerTask, 0, 5000); //
}
private void stopTimerTask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
Insert your processing code in Handler.post(). Then start the trigger by calling startTimer(). To stop the trigger, just call stopTimerTask().
this is a simple code to understand the runnable .I tried but not working . can you guys help me pls this is my code
public class Autostart extends activity implements Runnable {
#override
public void run (){
System.out.println ("message");
}
}
}
this not printing any statements
If you are using an Activity, you need to write your code inside Activity lifecycle methods. onCreate() is called when the Activity is created. So starting your Runnable here would be the correct way to do it.
#Override
public void onCreate(Bundle savedInstanceState) {
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
System.out.println ("message");
}
};
handler.postDelayed(r, 1000);
}
You have to create a Thread object and call start() using that object.
Thread t = new Thread(this);
t.start();
Or Just use Handler
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do Something here
}
}, 5000);
You can use below code to print a value after regular interval of time
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
Log.e("on print timee", your value);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); // will execute after 1 sec
}
Hope this will help you
I found a similar solution to Swayam (android implements runnable not working?), however another handler.postDelayed reference within run() was required;
public void onCreate(
...
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
Log.i(TAG, "message");
handler.postDelayed(this, 1000);
...
}
};
handler.postDelayed(r, 1000);
Try following code
Handler mainThreadhandler = new Handler(getMainLooper());
mainThreadhandler.post(new Runnable(){
public void run(){
// UI work
}
});
public class Autostart extends activity implements Runnable {
Thread = thread;
#override
public void onCreate() {
thread = new Thread(this);
thread.start();
}
#override
public void run (){
System.out.println ("message");
}
}
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 have an intentService that starts a handler, but after a certain amount of time I need to stop the handler. I'm not sure how to do this. I have the class below, but I'm just not sure how to stop the handler once the time is reached, or when a certain amount of hours/min passes. I would like this to be as efficient as possible please.
public class RedirectService extends IntentService {
private Handler handler;
private Runnable runnable = new Runnable() {
#Override
public void run() {
foobar();
handler.postDelayed(this, 2000);
}
};
public LockedRedirectService() {
super("RedirectService");
}
#Override
protected void onHandleIntent(Intent redirectIntent) {
// Gets data from the incoming Intent
int hour = redirectIntent.getIntExtra("hour", 0);
int min = redirectIntent.getIntExtra("minute", 0);
handler.postDelayed(runnable, 2000);
handler.removeCallbacks(runnable);
}
}
Start a new thread and wait. When time's up, stop and remove the runnable.
Or use handler to post another delayed runnable to stop and remove the working runnable.
public class RedirectService extends IntentService {
private Handler handler;
private boolean mRun = false;
private Runnable runnable = new Runnable() {
#Override
public void run() {
if (mRun) {
foobar();
handler.postDelayed(this, 2000);
}
}
};
public LockedRedirectService() {
super("RedirectService");
}
#Override
protected void onHandleIntent(Intent redirectIntent) {
// Gets data from the incoming Intent
final int hour = redirectIntent.getIntExtra("hour", 0);
final int min = redirectIntent.getIntExtra("minute", 0);
mRun = true;
handler.postDelayed(runnable, 2000);
//handler.removeCallbacks(runnable);
new Thread(new Runnable() {
#Override
public void run() {
Thread.currentThread();
try {
Thread.sleep((hour * 60 + min) * 60 * 1000);
} catch (Exception ignore) {}
mRun = false;
handler.removeCallbacks(runnable);
}
}).start();
/* or use handler
handler.postDelayed(new Runnable() {
#Override
public void run() {
mRun = false;
handler.removeCallbacks(runnable);
}
}, (hour * 60 + min) * 60 * 1000);
*/
}
}
This is my code on Activity to Invalidate the canvas it is not invalidating. Means onDraw() is not getting called even once;
public GraphView view;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = GraphView(this,null);
runplotTimer();
}
public void runplotTimer()
{
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
InvalidateTimer();
}
},1000,40);
}
public void InvalidateTimer()
{
this.runOnUiThread(new Runnable() {
#Override
public void run()
{
//Log.d(ALARM_SERVICE, "Timer of 40 miliseconds");
view.InvalidateGraph();
}
});
}
on View class this is method which is gettting called from Activity. other OnDraw declaration is same as required.
public void InvalidateGraph()
{
m_bCalledPlotRealTimeGraph = true;
invalidate(chanX_count1, 0, chanX_count1+7, graphheight);
}
Any help please ?
You are attempting to make changes to the View on a Timer Thread, which will not work. You need to call invalidate on the main (UI) thread:
((Activity) view.getContext()).runOnUiThread(new Runnable() {
#Override
public void run() {
invalidate(chanX_count1, 0, chanX_count1+7, graphheight);
}
});
you need to Start the Timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
InvalidateTimer();
}
},1000,40);
t.start()
Instead of Timer use Handler.
class UpdateHandler implements Runnable {
#Override
public void run(){
handler.sendEmptyMessageAtTime(0, 1000);
handler.postDelayed(this, 1000);
}
}
private Handler handler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//Call your draw method
}
}
};
Inside onCreate and onResule write
if( mupdateTask == null )
mupdateTask = new UpdateHandler();
handler.removeCallbacks(mupdateTask);
Call your handler using
handler.postDelayed(mupdateTask, 100);