Why do I see so many tutorials with the variables declared in OnCreate
and why doesn't it work for me?
Declaring variables within a method, or, outside, really boils down to what kind of scope
you want to associate with the variable.
Inside a method, you need to be careful that you're declaring a variable before you intend to use it.
Where is the appropriate place to declare them?
Appropriateness of where to declare a variable depends entirely on where all you want to use it. Declaring a variable at the class level, when you only intend to use it within a method is unwise. And declaring variables within methods, when a lot many other methods in the class want to access it, and you end up passing the variables to each method - is also unwise. So for now, you can just consider:
- Declare variables at class - when many methods in the class need to access it.
- Declare variable in methods - when only the method has use for the variable.
I'd like to add, that 1 and 2 are not universal rules that can be applied blindly - but to get off to a start, you can follow them, until you figure out the deeper nuances associated with variable scoping, access specification and lifetime.
I'm not talking about access specifiers here, since, they merit a much detailed understanding, which you can get here. And neither have i talked about the difference of instance vs. class variables here, because you'd be better of referring to an official doc like this one.
I understand the basics of encapsulation and inheritance, so is onCreate
just like any other method and any variables declared in there are isolated from other methods?
That's correct.
What about my buttons, should I declare those inside my class but outside the onCreate
?
UI components in Android are typically required by multiple methods to access. TextView
, Button
, etc - usually have states which need to be altered at different times, from different methods - so you'd be better off declaring them at the class level.
Another important reason why you should prefer declaring UI variables at the class level is that you reduce the overhead of having the Android framework create them for every method invocation. As long as your Activity
instance is alive, the framework holds onto the UI components/variables.