Search code examples
androidandroid-dialogfragment

Android How to call a fragment method from a DialogFragment positive button click


I have extended DialogFragment and am calling it from a Fragment (using support libraries eg. android.support.v4.app.Fragment)

The Fragment Implements the following interface containing doPositiveClick() method.

public interface CustomFieldsFragmentAlertDialog {
    public abstract void doPositiveClick();
}

To show the dialog, I call:

CustomFieldsDialogFragment dialog = CustomFieldsDialogFragment.newInstance();
dialog.show(getFragmentManager(), "fragmentDialog");

Here is my DialogFragment class

public static class CustomFieldsDialogFragment extends DialogFragment{          

        public static CustomFieldsDialogFragment newInstance() {

            CustomFieldsDialogFragment frag = new CustomFieldsDialogFragment();             
            return frag;
        }   


        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {               

            Builder builder = new AlertDialog.Builder(getActivity()); 
            builder.setTitle("Title");                
            builder.setPositiveButton(posButtonText, new DialogInterface.OnClickListener() {                        

                    @Override
                    public void onClick(DialogInterface dialog, int which) {                            
                        ((CustomFieldsFragmentAlertDialog)getTargetFragment()).doPositiveClick();

                    }
                });
            }                

            return builder.create();

        }       
    }

The application crashes with a null pointer exception when trying to execute the line ((CustomFieldsFragmentAlertDialog)getTargetFragment()).doPositiveClick();

10-05 13:45:23.550: E/AndroidRuntime(29228): java.lang.NullPointerException 10-05 13:45:23.550: E/AndroidRuntime(29228): at com.company.app.CustomFieldsFragment$CustomFieldsDialogFragment$1.onClick(CustomFieldsFragment.java:194)

How can I call the doPositiveClick() method that exists in the fragment that calls the CustomFieldsFragmentAlertDialog?

Note, The android developer site shows an example http://developer.android.com/reference/android/app/DialogFragment.html#AlertDialog that uses the line ((FragmentAlertDialog)getActivity()).doPositiveClick(); but I'm calling from a Fragment, not an activity.

Thanks,


Solution

  • In ((FragmentAlertDialog)getActivity()).doPositiveClick(); line the activity is implementing the Interface so that you can cast the activity into Interface class.

    In your case you want to cast the target fragment in to Interface so your target fragment must implement the interface else it will give you ClassCastException. But you are getting the NullPointerExeception so that be sure the getTargetFragment() method is not returning the null object.