I have some fragments in the app I'm working on. The default fragment is HomeFragment
. I successfully set the state of a FloatingActionButton in the HomeFragment to setEnabled(true)
or setEnabled(false)
based on the result of a method decideDisable()
when the activity is started afresh. But when I navigate to MyAccountFragment
or any other fragment using navigation drawer and I try to return to the home fragment the app crashes with the following error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.accessopthalmics.accessophthalmics, PID: 18211
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setEnabled(boolean)' on a null object reference
at com.app.Main2Activity.decideDisable(Main2Activity.java:333)
at com.app.Main2Activity$1.onNavigationItemSelected(Main2Activity.java:132)
at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:154)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:342)
at android.view.View.performClick(View.java:5210)
at android.view.View$PerformClick.run(View.java:21183)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5452)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:762)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
I use the following code to set HomeFragment
:
HomeFragment homeFragment = new HomeFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, homeFragment, "home");
ft.addToBackStack(null);
ft.commit();
return homeFragment;
Please note that I have to do an important check with decideDisable()
every time HomeFragment is loaded into view.