Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is onCreate() in Activity protected?

Why is the onCreate() in Activity protected?

or I should ask: why does it work?

Protected method can only be called in the inside of the class itself or it's descendants. So Android system can't call it like "act.onCreate()". So... how can it be called?

BTW, why is onClick() in OnClickListener is public? What's the difference?

like image 887
Lai Yu-Hsuan Avatar asked Apr 13 '11 16:04

Lai Yu-Hsuan


3 Answers

onCreate is not public because you don't want a random class in a totally different package creating an activity.

If I design an Activity class in a com.abccompany.activity package, and one of my co-workers designs a JSON data parsing class in a com.abccompany.jsonparser package, I don't want him creating my activity and displaying his JSON data whenever he wants.

onCreate is not private because you do want to subclass an Activity and then use the super Activity onCreate method for the subclass.

Actually every Activity you design extends android.app.Activity, so if onCreate was private in that super class, then you wouldn't be able to call onCreate at all.

like image 183
Lou Morda Avatar answered Nov 02 '22 16:11

Lou Morda


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

MyActivity activity = new MyActivity();
activity.onCreate(args);  // which doesn't make sense because activity is not yet created

Since this method is only called when the activity gets created, calling it yourself will most probably give you a nullpointerException because the activity is not yet created.

like image 39
Saadi Avatar answered Nov 02 '22 17:11

Saadi


It's useful to have public onClick methods because you can "force" certain buttons to be clicked programmatically. A common example of this is causing the same to code to execute when the user presses the enter key, or pressed the Submit button.

I don't think Android calls Activity.onCreate directly. Note that Activity inherits from Context (which does have a public constructor). It is my understanding that the constructor triggers some events to occur, and the onCreate/Pause/Resume/Destroy methods are called internally to the class at the appropriate time.

For example, when you create an activity, the view XML file has to be parsed and inflated. This happens automatically, so there's something happening behind the scenes that you don't directly control.

like image 40
Zach Rattner Avatar answered Nov 02 '22 17:11

Zach Rattner