Handler Runnable runs even after activity exit - android

I am updating the text user types in a textview to database every 5 seconds.
The handler collects data from textview and save it to database.
But the update code runs even after I press back button and return to MainActivity.
How can I stop running the code after exiting from activity.
public class CreateBoxActivity extends AppCompatActivity {
Long current_BoxID = null, parent_BoxID = null;
Handler h=new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_box);
h.post(new Runnable(){ //Run this every five seconds to update the data
#Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String editeddate = sdf.format(Calendar.getInstance().getTime());
String titleText = ((EditText)findViewById(R.id.new_box_title)).getText().toString();
String descriText = ((EditText)findViewById(R.id.new_box_descri)).getText().toString();
Boxes nbx = new Boxes(1, null , titleText, descriText, editeddate, editeddate);
BoxesController.UpdateBox(nbx);
h.postDelayed(this,5000);
}
});
}

You need to release the handler resource when the activity is destroyed.
#override
protected void onDestroy() {
super.onDestroy();
h.removeCallbacksAndMessages(null);
h = null;
}

Create runnable outside of the method like :
Runnable runnable =new Runnable() {
#Override public void run() {
}
};
On your activity's onPause call:
h.removeCallback(runnable);

You can remove the handler in onPause
Runnable runnable =new Runnable() {
#Override public void run() {
}
};
new Handler().removeCallbacks(runnable);

Related

I am looking to exit a handler and go back to activity code when it has done its job

I have been trying to figure out how to make a countdown timer using 'handler()' and i still don't know how to make it so the app will execute the line "Finished" when the countdown hits 0.
I am after whatever line of code is required for me to enter in the 'UpdateGUI()' to exit the runnable and go back to the main activity to display "Finished".
I have not been coding very long, so maybe it is an obvious answer, but I can't find it on any threads on this page...
Some help would be much appreciated :-)
Thank you
public class MainActivity extends AppCompatActivity {
int i = 10;
TextView tv;
final Handler myHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but = (Button) findViewById(R.id.button);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tv = (TextView) findViewById(R.id.textView);
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
UpdateGUI();
}
}, 0, 1000);
tv = (TextView) findViewById(R.id.textView);
tv.setText("Finished");
}
});
}
private void UpdateGUI() {
if (i == 0) {
//this is where i need to enter the code!!
}
else
i--;
myHandler.post(myRunnable);
}
final Runnable myRunnable = new Runnable() {
public void run() {
tv.setText(String.valueOf(i));
}
};
}
If I understand you correctly in case you need to run your runnable after some period of time use Handler method postDelayed(runnable, timeOutInMillis)
UPDATE: example of handler timer
int timesRun;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
runTimer();
i++;
}
};
// call it in button callback
public void runTimer(){
// update your timer here
if (i != 10) // if 10 seconds not passed run it one more time
handler.postDelayed(runnable, 1000); // run every second
}
Note that this is not the most elegant way to do this, but still, it should work

Update time display every minute, not just on create?

I want the activity time to update every minute, not just on create. This is the code I have so far:
public class MainActivity extends ActionBarActivity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TimeZone tz = TimeZone.getTimeZone("Atlantic/St_Helena");
Calendar c = Calendar.getInstance(tz);
String timez = String.format("Year "+"%02d" , c.get(Calendar.YEAR))
// Display formattedDate value in TextView
TextView time = new TextView(this);
time.setText("Its"+timez+" PM"+"\n\n"+"Ants stretch when they wake up in the morning.");
time.setGravity(Gravity.TOP);
time.setTextSize(20);
setContentView(time);
}}
Try to use a runnable and a handler like this:
handler=new Handler();
new Runnable() {
public void run() {
c = Calendar.getInstance(tz);
timez = String.format("Year "+"%02d", c.get(Calendar.YEAR));
time.setText("Its"+timez+" PM"+"\n\n"+"Ants stretch when they wake up in the morning.");
time.setGravity(Gravity.TOP);
time.setTextSize(20);
setContentView(time);
handler.postDelayed(this, 60000);
}
}.run();
This is the code i have so far
new Timer().schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
}
},0,1000);
What i want to do is replace the ,0,1000); at the end with something like 60 minutes - current time.

Updating a textview that shows current time every second or minute

Hi Iam trying to update 3 textviews every second. I have written this piece of code. the thread starts normally but the textviews they do not get updated. I am passing a function inside the text parameters of the texts views that gets the current system time (using Calendar) in digits but then converts it to letters. example: for 3.45 THREE FORTYFIVE. any help would be appreciated. thanks
public class MainActivity extends Activity {
TextView currentv;
GetDate gd;
TextView currentmin;
TextView currentmins;
private Handler mHandler;
private boolean Running = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentv = (TextView) this.findViewById(R.id.tvtimehour);
currentmin = (TextView) findViewById(R.id.tvtimemin);
currentmins = (TextView) findViewById(R.id.tvtimesecond);
gd = new GetDate();
currentv.setText(gd.calculateTimeHour());
currentmin.setText(gd.calculateTimeMinute());
currentmins.setText(gd.calculateTimeMinuteDigit());
mHandler = new Handler();
Runnable runb = new Runnable(){
#Override
public void run(){
while(Running == true){
try{
Thread.sleep(1000);
}
catch(Exception e){
e.printStackTrace();
}
mHandler.post(new Runnable(){
#Override
public void run(){
currentv.setText(gd.calculateTimeHour());
currentmin.setText(gd.calculateTimeMinute());
currentmins.setText(gd.calculateTimeMinuteDigit());
}
});
}
}
};
new Thread(runb).start();
}
Try this,
private MyTimerTask mytask;
private Timer timer;
mytask = new MyTimerTask();
timer = new Timer();
timer.schedule(mytask, 0,60000);
Timer class:
class MyTimerTask extends TimerTask {
#Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
// Do your stuff here it will work
currentv.setText(gd.calculateTimeHour());
currentmin.setText(gd.calculateTimeMinute());
currentmins.setText(gd.calculateTimeMinuteDigit());
}
});
}
}
Use Timer for this, I think because Thread can not update your UI.

Changing TextView text from a thread

I know you can only change the text in tTxtViews from the UI thread but i cant seem to find a way to work with that.
I'll go in to a bit more details: I'm trying to have a TextView that displays the time passed, but I can't do it in a thread, or a method that keeps getting called.
can you help me with a way of doing this? because I'm pretty much out of ideas.
Thanks.
public class MainActivity extends Activity {
protected static final long TIMER_DELAY = 100;
private TextView tv;
protected Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.helloWorld);
handler = new Handler();
handler.post(timerTask);
}
private Runnable timerTask = new Runnable() {
public void run() {
Calendar now = Calendar.getInstance();
//format date time
tv.setText(String.format("%02d:%02d:%02d", now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND)));
//run again with delay
handler.postDelayed(timerTask, TIMER_DELAY);
}
};
}
I forgot add this, sorry. Don't forget do this:
#Override
public void onPause() {
if (handler != null)
handler.removeCallbacks(timerTask);
super.onPause();
}
And if you want resume app try this
#Override
public void onResume() {
super.onResume();
if (handler != null)
handler.post(timerTask);
}
Use this
new Thread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// Do what you want.
}
});
}
}).start();
or use a Handler:
Runnable r = new Runnable() {
#Override
public void run() {
// Do what you want.
}
};
Handler mHandler = new Handler();
mHandler.post(r);

TimerTask doesn't take effect

Here's my code:
public class SomeName extends MapActivity implements OnClickListener, OnTouchListener{
public Timer t1 = new Timer();
public TimerTask tt;
public long interval = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.map);
timer();
}
public final void timer()
{
t1 = new Timer();
tt = new TimerTask() {
#Override
public void run() {
systemClick();
}
};
t1.scheduleAtFixedRate(tt, 10000, interval);
}
public void systemClick()
{
Toast.makeText(getApplicationContext(),"System Button Clicked", 5).show();
}
Actually, I want to call some function, where I refresh my location.
But I can't understand why I never get the toast on the screen.
I'm new to android.
Thanks for any help.
use handler in your Activity
final Handler handlerforadd = new Handler();
Runnable runnableforadd = new Runnable() {
#Override
public void run() {
handlerforadd.postDelayed(this, 1000);
}
};
handlerforadd.postDelayed(runnableforadd, 0);
The reason is the Toast has to be done on the UI thread. In your current code the method run() is being executed on a separate thread. I would suggest looking at this article on Processes and Threads. #parag is correct using a Handler is one way to get a reference to the UI thread but there are other methods.

Categories

Resources