Cannot create dialog inside a fragment

Viewed 77

I am trying to create a dialog inside a fragment.when I am trying to press on the button and enter the dialog the app collaspe. I guess the code is not right can you please help me with that?

Here is my code:

 private void openDialog(){


      Dialog dialog=new Dialog(getContext());
     //AlertDialog.Builder builder=new AlertDialog.Builder(getContext());

    LayoutInflater layoutInflater=this.getLayoutInflater();
        View custom_dialog=getActivity().getLayoutInflater().inflate(R.layout.geo_dialog,null);

     dialog.setContentView(custom_dialog);
    //   add_geofence_radius= custom_dialog.findViewById(R.id.radius_size);
        save_btn=custom_dialog.findViewById(R.id.save_btn);
        cancel_btn=custom_dialog.findViewById(R.id.cancel_btn);
      /*  save_btn.setOnClickListener(new View.OnClickListener() {
            @Override



            }
        });


       */
        /*cancel_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });

         */

   //    dialog.setTitle("hello");
     dialog.show();

    }

1 Answers

The best way to show dialog in android is to use "DialogFragments" since they are aware of the lifecycle of the view it is attached on (ie. fragments/activities).

Here is an examples provided in Android docs:

public class PurchaseConfirmationDialogFragment extends DialogFragment {
       @NonNull
       @Override
       public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
              return new AlertDialog.Builder(requireContext())
                    .setMessage(getString(R.string.order_confirmation))
                    .setPositiveButton(getString(R.string.ok), (dialog, which)    -> {} )
           .create();
       }

       public static String TAG = "PurchaseConfirmationDialog";
}

To show the dialog use:

new PurchaseConfirmationDialogFragment().show(
   getChildFragmentManager(), PurchaseConfirmationDialog.TAG);

For more reference on dialogFragments, checkout : Create a DialogFragment

Related