I have been wondering, as I'm new to Android, if it's bad practice to initialize a variable such as a Context object, in the fields declaration of a class before calling onCreate(). I am pasting a picture of what I'm talking about. Take a look at how and when I initialize the Context object. When is this instantiated compared to onCreate and can I trust it to be initialized everytime I call this class?
You can't use a context
before onCreate
is called. It won't be fully initialized. You can save it in a variable whenever though.
The real question is- why the heck are you doing this at all? There is no reason to save a copy of this in a class variable unless its static, since you can always reference it as this. And you should never save a static Context
.