Search code examples
androidandroid-dialogfragment

Showing DialogFragment


I have a class ActivityExitDialogFragment that extends android.support.v4.app.DialogFragment. There are only 2 methods in ActivityExitDialogFragment, onCreateDialog and newInstance to get a new instance of ActivityExitDialogFragment. Here they are:

public Dialog onCreateDialog(Bundle savedInstanceState) {
    String title = getArguments().getString("title");
Dialog myDialog = new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_launcher)
.setTitle(title)
.setNegativeButton("No", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // Dismiss the dialog.
        dismiss();
    }
    })
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // Close the Activity.
        getActivity().finish();
    }
}).create();

return myDialog;
}

static ActivityExitDialogFragment newInstance(String message) {
ActivityExitDialogFragment dialog = new ActivityExitDialogFragment();
Bundle args = new Bundle();
args.putString("title", message);
dialog.setArguments(args);
return dialog;
}

And here is the method used to show the dialog. Its in a different activity in the same package. It's called when the user clicks the exit button:

public void cancelButton(View v) {
    ActivityExitDialogFragment dialog =                        
    ActivityExitDialogFragment.newInstance(exitMessage);

    dialog.show(new FragmentActivity().getSupportFragmentManager(),               
    "Exiting");
}

Whenever I click the exit button I get an IllegalStateException at the dialog.show line. I had this problem before and it was because I didn't have the android-support-v4.jar file in the libs folder of my project. I put that jar file in the libs folder and it worked. I changed the name of the class from something else to ActivityExitDialogFragment and had eclipse change the name of the java file to match. And since then I'm getting this exception again. I dont know if its a coincidnece that I got the exception again after changing the name or if eclipse does something other that just change the name of the jar file to match the name of the public class. I have tried changing access modifiers for the getInstance method, deleting and adding a new copy of the android support jar file, changing the name back to the old name, and have been spending a few hours on Google but I have not found an answer yet.


Solution

  • You shouldn't try to directly instantiate an Activity with new. Instead get the fragment manager directly from the activity you have:

    dialog.show(getSupportFragmentManager(),               
    "Exiting");