Search code examples
androidcountdowntimeroncreatescreen-rotation

onCreate is called twice


I have 2 activities - MainActivity and page1. I have intent from the first like this:

 button_forward.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Intent intent = new Intent(MainActivity.this, Page1.class);
                startActivity(intent);
                return true ;
            }

However, my Page1 class's onCreate is called twice! i can detect it with toast message: it appears twice on the screen:

@Override
protected void onCreate(Bundle savedInstanceState) {

    Toast.makeText(Page1.this, "onCreate 1", Toast.LENGTH_SHORT).show();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.page1);
    //some code here like findview by id...
}
        });`

I do have some methods that use countdowntimer in my Page1 activity, timers that wait for 2 secs, i commented them out, but onCreate() still gets called twice.

I added code to prevent screen rotating, but the error persists


Solution

  • The problem is that your touch listener doesn't check which type of event we have, this means that your onTouch should be called like 100 times per second, but it actually is called only twice because the new Activity UI covers the button. Use this code to check which event we have:

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() != MotionEvent.ACTION_DOWN) return false;
        Intent intent = new Intent(MainActivity.this, Page1.class);
        startActivity(intent);
        return true;
    }
    

    If the action is ACTION_DOWN it means that the user has just touched the button. If it is ACTION_UP it means that the user lifted his / her finger.