0

I am launching a DialogFragment from my Fragment and listening to an event in MainActivity when the button is pressed in Dialog Fragment.

This is the listener interface defined in DialogFragment :

public interface NewDialogListener {
    public void onDialogPositiveClick(String data);
}

Instantiating the listener in DialogFragment:

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    // Verify that the host activity implements the callback interface
    try {
        // Instantiate the NoticeDialogListener so we can send events to the host
        mListener = (NewDialogListener) activity;
    } catch (ClassCastException e) {
        // The activity doesn't implement the interface, throw exception
        throw new ClassCastException(activity.toString()
                + " must implement NoticeDialogListener");
    }
}

@Override
public AlertDialog onCreateDialog(Bundle savedInstanceState) {
    currentActivity = getActivity();
    newDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(positiveButtonViewOnClickListener);
 ...
return newDialog;
}

Firing the listener when positive button in DialogFragmentis clicked:

private DialogInterface.OnClickListener positiveButtonOnClickListener = new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {

        mListener.onDialogPositiveClick("positive");
    }
};

And then I capture the listener in MainActivity :

@Override
public void onDialogPositiveClick(String status) {
    Fragment fragment = getVisibleFragment();
    if (fragment instanceof  NewListFragment) {
        ((NewListFragment)fragment).updateView();
    }
}

This works if I haven't changes the rotation of the device. But If I changes the rotation of the device and do the same thing again, the control never reaches onDialogPositiveClick.

What is that changes when device is rotated that could cause this?

user1324887
  • 632
  • 3
  • 11
  • 32

1 Answers1

0

Since the listener is the activity itself, you can just use it directly in the onClick via a call to getActivity(). You can put a try catch on the call to be safe. No need to set it to a variable.

lionscribe
  • 3,413
  • 1
  • 16
  • 21
  • Not sure If I understand that correctly. Do you mind posting an example? – user1324887 Jul 31 '16 at 05:33
  • private DialogInterface.OnClickListener positiveButtonOnClickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { ((NewDialogListener)(getActivity()).onDialogPositiveClick("positive"); } }; – lionscribe Jul 31 '16 at 05:40
  • Reason being, I suspect that mListener is not valid for some reason after rotation. – lionscribe Jul 31 '16 at 05:50
  • possible, and it doesn't happen all the time. So your reasoning makes sense. I will try it out. – user1324887 Jul 31 '16 at 05:54