'java.lang.IllegalStateException: View com.google.android.material.button.MaterialButton ... does not have a NavController set

For a bit of context, I'm doing a learning app, when the user reach the end of the lesson a dialog shows but when I click the "go back" option to return to the previous fragment (the app is designed with a Navigation object and different fragments) I get the error on the title.

@Override
    public void onClick(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.btnL:
                if (pagina == 1) {
                    Toast toast = Toast.makeText(getContext(), "Estás al principio", Toast.LENGTH_SHORT);
                    toast.show();
                } else {
                    llenarDatos(--pagina, datos);
                }
                break;
            case R.id.btnR:
                if (pagina < limite)
                    llenarDatos(++pagina, datos);
                else
                    showDialog(view);
                break;
            case R.id.btn_no:
                bundle.putBoolean("modo", true);
                Navigation.findNavController(view).navigate(R.id.fragment_menu, bundle);
                break;
            case R.id.btn_yes:
                break;
        }
    }

The case R.id.btn_no is the option with the error.

Dialog code:

 private void showDialog(View v) {
        dialog = new Dialog(getContext());
        dialog.setContentView(R.layout.custom_dialog);
        Button btnVolver = dialog.findViewById(R.id.btn_no);
        Button btnExamen = dialog.findViewById(R.id.btn_yes);
        btnVolver.setOnClickListener(this);
        dialog.show();
    }

I've read in another post that this happens because the dialog dismiss when pressing the button, so it doesn't exist anymore. How can I solve it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source