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?
Asked
Active
Viewed 1,121 times
2 Answers
-1
initialize Context inside onCreate() that will not fail. It will initialize everytime when you call this class.

P. Jaiswal
- 205
- 1
- 2
- 11
-1
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
.

KeLiuyue
- 8,149
- 4
- 25
- 42

Gabe Sechan
- 90,003
- 9
- 87
- 127
-
What about other variables? Is it unwise to initialize an array before on create. I’m not saying these are tactics I’m using but by accident I realized it worked. I just want to fully understand it. So other than the context, is it just as unwise to initialize variables like lists and others? – Sep 30 '17 at 02:32
-
No, there's no problem instantiating lists or the like that way. The only problem is if the right hand side of the equal includes a call to a variable that is not yet fully initialized (requires a call other than its constructor to be fully usable). That's fairly rare, but Contexts are notable exceptions. Whether you should or not is more a personal style choice. – Gabe Sechan Sep 30 '17 at 02:35
-
As the pciture shows you "can",as it compiles, so the answer is wrong. You "shouldn't" because it might be null, is a different topic – CaptainCrunch Nov 20 '20 at 14:15
-
@CaptainCrunch No, you can't. It will compile, but the variable will not be initialized and will not work properly. So you can't *actually* do it. The fact that it compiles doesn't mean it works. And in this case you're wrong it can't be null, as the this keyword is never null. – Gabe Sechan Nov 20 '20 at 15:07