Vitaly Sulimov
Vitaly Sulimov

Reputation: 106

Android. It's okay to init objects outside of onCreate() lifecycle method?

I have some utils and workers in my project. All of these classes works as singleton. Suppose that I have multimple activities where this objects used but is there a difference between

private LocationWorker mLocationWorker;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_daily_forecast);
    mLocationWorker = LocationWorker.getInstance();

and this?

LocationWorker mLocationWorker = LocationWorker.getInstance()

It's okay to get references to this objects before onCreate() method?

Upvotes: 0

Views: 1066

Answers (2)

Vishavjeet Singh
Vishavjeet Singh

Reputation: 1385

I usually prefer the first approach

private LocationWorker mLocationWorker;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_daily_forecast);
    mLocationWorker = LocationWorker.getInstance();

because the object will be created only when needed. In the second approach you are creating a singleton object. The object takes memory even before when it is needed. Some situations I prefer the first approach are:

  • If the same object will be used from different parts of the activity. Thus you do not want to check for null every time before use want a clean code and you want cleaner code.
  • If there will be a single common object for the class that will not change through out. Usually you make it static. Good example is: String LOG_TAG = MyActivity.class.getSimpleName();
  • If the object will be used frequently in your activity. For activity that makes frequent communication with the server, for example, you should create the object of the class which makes the communication this way. Additional example is

If the object will be used in certain part of the class, you should consider declaring it inside that class.

Upvotes: 2

Paul Boddington
Paul Boddington

Reputation: 37645

It's okay to get references to this objects before onCreate() method?

Yes it is.

LocationWorker mLocationWorker = LocationWorker.getInstance();

should work fine.

However, since it is a singleton, I'm not sure there's much point saving a reference to it in a field. You could just do

LocationWorker.getInstance()

whenever you need it.

Upvotes: 1

Related Questions