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 trialKeivan Norouzi
4,513 PointsWhy 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
56,414 PointsFrom 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.
Doug Ray
7,493 PointsThis 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
4,513 PointsGood point, Thanks a lot :)
Keivan Norouzi
4,513 PointsKeivan Norouzi
4,513 PointsThank you so much. It helped a lot :)