I am basically asking about the difference between these two approaches:
public class myClass extends AppCompatActivity {
private objectType mObject = new objectType();
@Override
protected void onCreate(Bundle savedInstanceState) {
//do stuff with mObject
and
public class myClass extends AppCompatActivity {
private objectType mObject;
@Override
protected void onCreate(Bundle savedInstanceState) {
mObject = new ObjectType();
I hope I'm being clear enough. I am struggling to understand when we'd want to choose one versus the other.
An Activity has a well defined lifecycle, as you probably know. It does not always matter if you create new instances in the constructor vs. onCreate, but you would definitely prefer onCreate in these circumstances:
Functionally, nothing.
The first one will be created when the Activity object is created (
new myClass()
is called). The Android system does this at some point during creation.The second one will be created when the system eventually calls
onCreate()
.The gotcha would be if you had an object that needs a
Context
in the constructor. You could do this for example:And the app will suddenly crash because you most likely will try to extract resources from the
Context
that don't exist yet. (Remember, the Activity isn't created at this point).So, if your object does have to use
Context
, then you have to create it at or afteronCreate
is called.