Yesudass Moses
Yesudass Moses

Reputation: 1859

Handler Runnable runs even after activity exit

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

Upvotes: 2

Views: 1081

Answers (3)

Md Sufi Khan
Md Sufi Khan

Reputation: 1761

Create runnable outside of the method like :

Runnable  runnable =new Runnable() {
  @Override public void run() {

  }
};

On your activity's onPause call:

h.removeCallback(runnable);

Upvotes: 2

Raja Jawahar
Raja Jawahar

Reputation: 6962

You can remove the handler in onPause

Runnable  runnable =new Runnable() {
      @Override public void run() {

      }
    };
    new Handler().removeCallbacks(runnable);

Upvotes: 1

Hussain
Hussain

Reputation: 1335

You need to release the handler resource when the activity is destroyed.

@override
protected void onDestroy() {
    super.onDestroy();
    h.removeCallbacksAndMessages(null);
    h = null;
} 

Upvotes: 3

Related Questions