android implements runnable not working? - android

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");
}
}

Related

Can my code be suspected of memory leak in android?

I use code like below for periodic execution
but i am suspecting a memory leak
Maybe my code is wrong?
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
if(isRunning)
{
...code
}
handler.postDelayed(this, 5000);
}
};
handler.postDelayed(runnable, 5000);
This is the code that uses another handler
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
mHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(#NonNull Message msg) {
return true;
}
});
}

Android studio update textview every 5 seconds

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);

Error inside the class

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();

Remove postDelayed in android

I am using postDelayed with TextView to hide it after some time. Now, I want to remove postDelayed if user click on button.
My code is as below :
tvRQPoint.setText("+100");
tvRQPoint.postDelayed(new Runnable() {
public void run() {
tvRQPoint.setText("");
}
}, 10000);
How to do this ?
Create your thread in separate place below...
private Runnable mTimerExecutor = new Runnable() {
#Override
public void run() {
tvRQPoint.setText("");
}
};
Then call it as follows to execute....
tvRQPoint.postDelayed(mTimerExecutor, 10000);
When you want to cancel the postDelay execution then cancel as follows...
tvRQPoint.removeCallbacks(mTimerExecutor);
check this
Runnable runnable = new Runnable() {
public void run() {
tvRQPoint.setText("");
}
};
tvRQPoint.setText("+100");
tvRQPoint.postDelayed(runnable, 10000);
to remove it
tvRQPoint.removeCallbacks(runnable);
boolean clicked=false;
onClick event
clicked=true;
and in postDelayed
tvRQPoint.setText("+100");
tvRQPoint.postDelayed(new Runnable() {
public void run() {
if(!clicked)
tvRQPoint.setText("");
}
}, 10000);
Use below code inside onClick. It will remove.
private final Runnable r = new Runnable() {
public void run() {
tvRQPoint.setText("");
Handler handler = new Handler();
handler.postDelayed(this, 2000);
}
}
};
and then use this inside onClick of button
handler.removeCallbacks(r);
For more information check this link

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