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!

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 an Interactive Story App (Retired) Finishing the User Interface Loading the First Page

Keivan Norouzi
Keivan Norouzi
4,513 Points

Why don't we set the member variables right away where we have declared them first?

It is not clear for me that why setting the member variables have to be done inside the onCreate() method and not where we first create them as global variables? I'd appreciate it if someone explain it to me. Thanks

2 Answers

Seth Kroger
Seth Kroger
56,412 Points

From the video, the member variables you're referring to are UI elements of the Activity. Those UI elements won't exist until the call to setContentView() at the start of onCreate(), so the findViewById() method would fail to return anything before them.

Keivan Norouzi
Keivan Norouzi
4,513 Points

Thank you so much. It helped a lot :)

Doug Ray
Doug Ray
7,493 Points

This kind of logic is also true for other types of member variables not necessarily just what you will use in the on create method. For example you may want to declare String[] mData; but will not receive the actual data until after a certain point :).

Keivan Norouzi
Keivan Norouzi
4,513 Points

Good point, Thanks a lot :)