0

I have an Activity A. And in stepperLayout of this activity I use Fragment B. I call dialogFragment C from Fragment B. Than on DialogFragment C i call listenerInterface method but listener Interface is null. So there was a null pointer exception. Activity A not implement the interface. Only fragment B implements it.

 My Fragment B

 dialogFragmentC = DialogFragmentC .newInstance();
 dialogFragmentC .show(getFragmentManager(), "");

My DialogFragment C

 @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            this.listener = (DialogFragmentListener) context;
        } catch (Exception e) {
            Timber.i(e);
        }
    }
Shockelduck
  • 65
  • 1
  • 2
  • 15

1 Answers1

0

Since you launch a dialog fragment from a fragment, the traditional way won't work.

Solution 1:

Use child fragment manager to launch: dialogFragmentC.show(getChildFragmentManager(), ""); and then check parent fragment: this.listener = (DialogFragmentListener) getParentFragment();

Solution 2:

Use target fragment: Android - getTargetFragment and setTargetFragment - What are they used for. Set the target fragment of your dialogFragmentC to FragmentB when you create dialogFragmentC and use getTargetFragment in the dialogFragmentC to get the listener.

Dewey Reed
  • 4,353
  • 2
  • 27
  • 41