Search code examples
androidandroid-alertdialogandroid-dialogfragment

Android: Alert Dialog using DialogFragment is not showing up


I'm trying to create a Alert Dialog but it doesn't show it and continues to process the next line of code. I've thoroughly searched but couldn't get any answer to this.

This is my fragment which is quite simple

public class AlertDialogFragment extends DialogFragment {

  public static AlertDialogFragment newInstance(int title) {
    AlertDialogFragment frag = new AlertDialogFragment();
    Bundle args = new Bundle();
    args.putInt("title", title);
    frag.setArguments(args);
    return frag;
  }

  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    int title = getArguments().getInt("title");

    return new AlertDialog.Builder(getActivity())
            ./*setIcon(R.drawable.alert_dialog_dart_icon)
            .*/setTitle(title)
            .setPositiveButton("Close",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                        }
                    })
            ./*setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                        }
                    }).*/create();
  }
}

Code in my activity to display the dialog, but it skips it and moves onto the next line without displaying the dialog pop-up

DialogFragment alertDialogFragment = AlertDialogFragment
                    .newInstance(R.string.alert_dialog_title);
alertDialogFragment.show(getSupportFragmentManager(), "dialog");

/**
 * Forward to next Activity
 */
Intent intent = new Intent(this, SelectResponsibilityActivity.class);
startActivity(intent);

Not sure where the problem is. Any help would be appreciated.


Solution

  • DialogFragment is attached to its activity. When you start another activity, the activity your dialog fragment is attached is not visible anymore, so is your fragment.

    Indirect implications are all over this documentation

    -You can add a button to your DialogFragment and do this in its onClick

    public void onClick (DialogInterface dialog, int whichButton){
        finish();
        startActivity(getIntent())
    }
    

    -Or you can just reload the activity using the following code, without onClick, and show your dialogFragment in the new activity

    finish();
    startActivity(getIntent())
    

    of course you will have to set some flags or something like that before you start the new activity and check for that flag in your onCreate(). Only if it's set, then show your dialogfragment.