0

In the fragment whenever I click the back button of the provided in navigation Graph the application crashes.

what I really want to implement is to display a dialog box that will say yes then will move to the previous fragment and if it says no then stay on the current fragment. But right now I was trying to display toast which is also not working. Please help

The code I used to handle this back button is:

OnBackPressedCallback callback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                if (mTimeLeft != 0) {
                    
                    Toast.makeText(getContext(), "It is not allowed for now later it will give alert dialog to cancel the exam", Toast.LENGTH_SHORT).show();
                }
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(requireActivity(), callback);

ERROR

java.lang.NullPointerException: Attempt to invoke virtual method 'androidx.appcompat.app.ActionBar androidx.appcompat.app.AppCompatActivity.getSupportActionBar()' on a null object reference
Garvit
  • 94
  • 11
  • 1
    you should also post the log for the crash. IMHO I think the crash is due to getContext() = null, – Umair Sep 07 '20 at 11:19
  • postup full code where you declared this--> getSupportActionBar() @Gravit – Wini Sep 07 '20 at 11:26

0 Answers0