Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Simple Android App (2014) Basic Android Programming Introduction to Methods and Classes

Holly Fox
Holly Fox
2,808 Points

Do you always use the OnCreate method in every android programme?

I'm still learning so just trying to understand the structure of android programming.

I just want to understand how things are run and how things are called.

Is OnCreate the main or central piece of code that everything else is called from ? If so, is OnCreate a piece of code which is common to every app?

I hope my question is clear enough and isnt as muddled as my brain right now!

Appreciate some help.

Thank you.

2 Answers

Hi Holly, the documentation helps a lot with those things. On it, it says: "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."

You can read more about that here Activity.

Also yes you'd see the on create method on all apps because without it, you can't connect the elements of the XML code (UI) with the java code you are programming.

onCreate() is NOT required for apps. But, the reason it is common to every single app is because that method is typically the best place to put initialization code. You could also put that same exact initialization code in onStart() or onResume() and when you first load the app, it will appear the same. Though, within onCreate() is typically the first time in the code that you call those initializations properly. And, basically, having the initialization there is typically better for overall performance, especially when you have multiple pages. (Explaining this fully could take up an entire course ;))

A very important part of Android is understanding the "Activity Lifecycle". You can find diagrams online for this or you can add debugging statements to your code to get a better feeling of when each method is called by the system.