Android: When is onCreateOptionsMenu called during Activity lifecycle?

Christopher Perry picture Christopher Perry · Oct 9, 2011 · Viewed 75.4k times · Source

I put a couple of breakpoints in onCreate (one at the beginning, and one at the end of the method), and I also put one at the beginning of onCreateOptionsMenu. The onCreate method is called first, and before it finishes onCreateOptionsMenu is called.

I'm trying to separate the Fragment navigation code in my app, so I have a couple of objects that I delegate onCreateOptionsMenu to depending on if the app is running on phone/tablet (I'm using screen size to determine this, my layout file for large screens has a View I check for after the layout is inflated). The problem I'm having is, I create these objects in onCreate, and I'm getting a null pointer exception when I reference the object in onCreateOptionsMenu.

Answer

CommonsWare picture CommonsWare · Oct 9, 2011

The onCreate method is called first, and before it finishes onCreateOptionsMenu is called.

That will be true on devices and apps with an official Honeycomb-style action bar. If there is no action bar, onCreateOptionsMenu() should not get called until the user calls up the menu, typically by pressing the MENU button.

(I'm using screen size to determine this, my layout file for large screens has a View I check for after the layout is inflated)

That test will break very shortly, once Ice Cream Sandwich ships. From what I can tell, ICS phones will have action bars (though perhaps not system bars).