Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the Android constructor and onCreate()?

Tags:

java

android

I'm a little confused by the difference between Java and Android Java. Let's say I have an Activity class AndroidX. There is no main function and there is no AndroidX() constructor as we know it. I realize that onCreate() most probably initializes the AndroidX Activity, but why is there no main? What's the difference?

like image 503
Lews Therin Avatar asked Aug 01 '11 14:08

Lews Therin


4 Answers

Consider that your activities are many *main*s and your manifest directs the execution to one of them.

Also consider that the constructor as we know it before is hidden and now it is always called onCreate()

Fair enough to keep going?

like image 127
Sherif elKhatib Avatar answered Nov 09 '22 01:11

Sherif elKhatib


This graphic may help some. http://developer.android.com/images/activity_lifecycle.png

In the Activity documentation they elaborate on what each function is meant for (i.e. onCreate(), onResume(), etc). http://developer.android.com/reference/android/app/Activity.html

like image 27
NeilMonday Avatar answered Nov 09 '22 01:11

NeilMonday


There is no "main" because that assumes that your app is either running or not running. But on android there are many other possible states your app could be in paused, stopped, started, etc...

Check out this link for an excellent overview of the Android Activity lifecycle.

like image 1
FoamyGuy Avatar answered Nov 09 '22 00:11

FoamyGuy


How onCreate works is described in the Activity page of the Android Developer Reference. Specifically here:

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.

In a sense you can consider this method the constructor for your Activity, as the initialization is handled there (see the Activity Lifecycle).

As for main, consider it hidden from you. Generally what you do is register listeners for UI elements such as buttons or text fields, then act on input from those UI elements. These listeners handle calls to your methods which might manipulate data or change how the UI displays.

like image 1
thegrinner Avatar answered Nov 08 '22 23:11

thegrinner