2

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

3 Answers 3

3

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

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

Create runnable outside of the method like :

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

  }
};

On your activity's onPause call:

h.removeCallback(runnable);
1

You can remove the handler in onPause

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.