Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do OnCreate should be called only once on the start of Activity?

I would like to know, why OnCreate() is called only once at the start of an activity?

Can we call OnCreate() more than once in the same activity?

If yes, than how can we call it? can anyone give an example?

Thanks a lot!!!

like image 452
G M Ramesh Avatar asked Dec 20 '12 03:12

G M Ramesh


People also ask

Is onCreate only called once?

OnCreate is only called once.

Why onCreate is called twice?

OnCreate will only be called one time for each lifetime of the Activity. However, there are a number of situations that can cause your activity to be killed and brought back to life. Thus, onCreate will be called again.

What method is called when the activity is called for the first time?

in short onCreate is called first and when you comeback from an activity onResume will be called. onResume will also be called the first time as well.

Why do we need to call setContentView () in onCreate () of activity class?

As onCreate() of an Activity is called only once, this is the point where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById to programmatically interact with widgets in the UI, calling managedQuery(android.


1 Answers

Why would you want to called it again? unless the activity is reconstructed, which is called by system. You cannot call OnCreate manually , it is the same reason why you won't call setContentView() twice. as docs:

onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically. Once you finish init your widgets Why would you?

UPDATE I take some words back, you CAN do this manually but I still don't understand why would this be called. Have you tried Fragments ?
Samplecode:

public class MainActivity extends Activity implements OnClickListener {
        private Button btPost;
        private Bundle state;
        private int counter = 0;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            state = savedInstanceState;
            btPost = (Button) findViewById(R.id.btPost);
            btPost.setOnClickListener(this);
            Toast.makeText(getBaseContext(), " " + counter, Toast.LENGTH_LONG)
                    .show();
        }

        @Override
        public void onClick(View v) {
            counter++;
            this.onCreate(state);
        }
    }
like image 169
wtsang02 Avatar answered Oct 14 '22 16:10

wtsang02