Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Activity Constructor vs onCreate

I understand that Android Activities have specific lifecycles and that onCreate should be overridden and used for initialization, but what exactly happens in the constructor? Are there any cases when you could/should override the Activity constructor as well, or should you never touch it?

I'm assuming that the constructor should never be used because references to Activities aren't cleaned up entirely (thus hampering the garbage collector) and that onDestroy is there for that purpose. Is this correct?

like image 283
idolize Avatar asked Jul 21 '10 17:07

idolize


People also ask

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

onCreate() method calls the setContentView() method to set the view corresponding to the activity. By default in any android application, setContentView point to activity_main. xml file, which is the layout file corresponding to MainActivity.

Is OnCreate called only once?

OnCreate is only called once.

Why is OnCreate protected?

the onCeate() is protected so to avoid calling of it from the activity object.

What is Android constructor?

A constructor is a special method that is called whenever an object is created using the new keyword. It contains a block of statements that is used to initialize instance variables of an object before the reference of this object is returned by new.


2 Answers

I can't think of any good reason to do anything in the constructor. You never construct an activity directly, so you can't use it to pass in parameters. Generally, just do things in onCreate.

like image 147
Cheryl Simon Avatar answered Oct 21 '22 13:10

Cheryl Simon


A good reason for putting things in the constructor as Gili's comment had stated is the use of final fields.

However, if you initialize things in the constructor, then the lifespan of the object will be a little bit longer, though I don't think by much because the onCreate would be called shortly thereafter.

Although it's against my ideal, I do avoid the constructor for initialization of the activity members and rely on onResume() and onPause() for resources that my app is dealing with.

For onCreate() I usually use it to do view mapping to local variables. Though android-annotations already does that for me so I rarely have an onCreate() method for my Activity. I still use it in Service though.

However, if you look at the members you may be initializing

  • they would have a "close" method that you have to invoke at the proper time (onResume or onPause)

  • they would be part of the view which means it needs to be initialized then onCreate needs to be called

  • they are constants which don't need to be put in the constructor anyway, just a static final would do. This includes Paint and Path constants which can be initialized by a static block

like image 22
Archimedes Trajano Avatar answered Oct 21 '22 14:10

Archimedes Trajano