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.
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 :)