ViT-Vetal-
ViT-Vetal-

Reputation: 2471

setContentView in ActionBarActivity and FragmentActivity

In FragmentActivity, the order of super.onCreate and setContentView isn't important, why?

FragmentActivity

//OK
@Override 
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_waiting_for_confirmation_order);
}

//OK
@Override 
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_waiting_for_confirmation_order);
    super.onCreate(savedInstanceState);
}

But in ActionBarActivity, it throws a NullPointerException.

ActionBarActivity

//OK
@Override 
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_waiting_for_confirmation_order);
}

//ERROR
@Override 
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_waiting_for_confirmation_order); //NullPointerException
    super.onCreate(savedInstanceState);
}

Upvotes: 1

Views: 567

Answers (1)

pdegand59
pdegand59

Reputation: 13039

The reason is ActionBarActivity (from support-v7) is using a delegate object to either use the real implementation or the compat implementation.

This delegate is instantiated in the method onCreate() of ActionBarActivity and the method setContentView() of ActionBarActivity is simply doing delegate.setContentView().

That's why there's a NPE if you call setContentView() before onCreate().

In FragmentActivity, (or standard Activity actually), the order doesn't matter because setContentView() doesn't rely on a specific object that could have been instantiated in onCreate().

Upvotes: 1

Related Questions