2

I have an MainActivty which consists of a Navigation Drawer. The navigation drawer code is pretty close to the official documentation. Now the MainActivty loads FragmentA upon start. The Navigation Drawer is supposed to be only available from FragmentA. So far so good, all works fine.

Now I tap something on the screen, which the MainActivity recognizes, and replaces FragmentA by FragmentB. When I am on FragmentB, in the FragmentB.onCreate() I call the following:

 setHasOptionsMenu(true);
((MainActivity)getActivity()).mDrawerToggle.setDrawerIndicatorEnabled(false); //ActionBarDrawerToggle mDrawerToggle is a public class variable in MainActivity

This is in order to replace the Drawer carat in the actionbar with a Back arrow. This works fine as well.

Now, at this point, if I change the screen orientation the MainActivty.onCreate() is not called. The FragmentB.onCreate() is still called, and the mDrawerToggle is null as the MainActivity.onCreate() was not called. So the app crashes due to a NullPointerException.

I am NOT using: android:configChanges="orientation" for the activity. I am not sure how to fix this, as the example code in Android documentation has only a single Activity and no other fragments. Any help is appreciated.

rgamber
  • 5,749
  • 10
  • 55
  • 99
  • **Hint:** When you want your `Fragment` to change the `ActionBar`, simply call `fragmentToSwitchTo.setHasOptionsMenu(true)` before you commit your `FragmentTransaction` and then call `invalidateOptionsMenu()`. Overriding `onCreateOptionsMenu()` will then work inside the `Fragment` just like an `Activity`. – Tamby Kojak Apr 10 '14 at 05:32
  • Hi, not sure how overriding `onCreateOptionsMenu` will help. Can you elaborate please? – rgamber Apr 10 '14 at 06:09
  • I'm not saying it'll help your current problem, I wouldn't posted an answer if that was the case. But it seems that you think one has to call `((MainActivity) getAcitivty())` to edit the `ActionBar`. Once you have many fragments this can be cleaned up by doing the above method. – Tamby Kojak Apr 10 '14 at 06:38

1 Answers1

0

Found the solution. It was a silly mistake. The Fragments onCreate() is called before the Activity's onCreate(). So I just put the code referring to the Activity in the Fragment.onCreateView(). Now all is well :)

rgamber
  • 5,749
  • 10
  • 55
  • 99