Search code examples
androidandroid-lifecycletoast

Android activity lifecycle confused between calls of function


When I run this app I am getting "On Resume" first instead of "On start" even "On create" not showing up, please tell me why? and "On Restart" toast is not displaying but test is getting updated.
public class MainActivity extends AppCompatActivity {

    public int test=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast t=Toast.makeText(getApplicationContext(),"On create",Toast.LENGTH_SHORT);
        t.setGravity(Gravity.CENTER_VERTICAL,20,20);
        t.show();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Toast t=Toast.makeText(getApplicationContext(),"On restart",Toast.LENGTH_LONG);
        t.setGravity(Gravity.CENTER_VERTICAL,20,20);
        TextView num=(TextView) findViewById(R.id.textNum);
        test++;
        num.setText(String.valueOf(test));
        t.show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Toast.makeText(getApplicationContext(),"On start",Toast.LENGTH_SHORT).show();
    }
    @Override
    protected void onResume() {
        super.onResume();
        Toast t=Toast.makeText(getApplicationContext(),"On resume",Toast.LENGTH_SHORT);
        t.setGravity(Gravity.CENTER_VERTICAL,10,20);
        t.show();
    }

    @Override
    protected void onPause() {
        super.onPause();
       Toast t= Toast.makeText(getApplicationContext(),"On Pause",Toast.LENGTH_SHORT);
       t.setGravity(Gravity.CENTER_VERTICAL,20,20);
       t.show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Toast.makeText(getApplicationContext(),"On Stop",Toast.LENGTH_SHORT).show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Toast.makeText(getApplicationContext(),"On destroy",Toast.LENGTH_SHORT).show();
    }
}

Solution

  • Using Toast as a debugging method is really bad idea. Use logging and look at your logcat. You will see that the methods get called in the order that they should. Just don't do this.