Skip to content

Instantly share code, notes, and snippets.

@Joev-
Last active June 25, 2021 08:43
Show Gist options
  • Save Joev-/5695813 to your computer and use it in GitHub Desktop.
Save Joev-/5695813 to your computer and use it in GitHub Desktop.
Getting results from DialogFragment to calling Fragment using Callbacks

##Getting results from DialogFragments to another Fragment.

When setting up the DialogFragment make a call to Fragment.setTargetFragment()
Then from DialogFragment you can access the main fragment with Fragment.getTargetFragment()
Use interfaces to provide the required actions to the calling Fragment.

##Example code.

###AddFriendDialogFragment - Calls back to calling fragment.

public class AddFriendDialogFragment extends SherlockDialogFragment {
    private OnAddFriendListener callback;

    public interface OnAddFriendListener {
        public void onAddFriendSubmit(String friendEmail);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
             callback = (OnAddFriendListener) getTargetFragment();
         } catch (ClassCaseException e) {
             throw new ClassCastException("Calling Fragment must implement OnAddFriendListener"); 
         }
    }
    
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getSherlockActivity());
        builder.setTitle(R.string.dialog_add_friend)
                .setMessage(R.string.dialog_add_friend_text)
                .setView(editText)
                .setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // Grab the text from the input
                        final String friendEmail = editText.getText().toString();
                        callback.onAddFriendSubmit(friendEmail);
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        AddFriendDialog.this.getDialog().cancel();
                    }
                });
        return builder.create();
    }

###Main fragment which displays the dialog and receives the callbacks from the dialog.

public class FriendsFragment extends SherlockListFragment implements OnAddFriendListener {
    
    ...

    private void showDialog() {
        FragmentManager fm = getSherlockActivity().getSupportFragmentManager();
        AddFriendDialogFragment addFriendDialog = new AddFriendDialogFragment();
        addFriendDialog.setTargetFragment(this, 0);
        addFriendDialog.show(fm, "add_friend_dialog");
    }

    @Override
    public void onAddFriendSubmit(String friendEmail) {
        // Do stuff
    }
}
@noloman
Copy link

noloman commented Apr 1, 2017

awesome, thanks a lot!

@KS-NZ
Copy link

KS-NZ commented May 11, 2017

I can't thank you enough, it took me two days to find this code, bravo!

@ArdenDev
Copy link

Thanks for the gist. Don't you need to create the onAttach overrides ? I have that in my code but the listener does not get initialized.

@prbale
Copy link

prbale commented Sep 26, 2017

Nice

Copy link

ghost commented Dec 17, 2017

Great Solution!!!

@trynx
Copy link

trynx commented Apr 20, 2018

Man ... you're a life saver !!
Was stuck with this a couple of hours .. Y_Y

@DevMensIT
Copy link

java.lang.NullPointerException: Attempt to invoke interface method 'void com.nodomain.kishan.example.Customs.SearchCustomDialog$SearchCustomDialogListener.onSearchDialogSubmit(java.lang.String, java.lang.String)' on a null object reference

don't know why i'm getting this....!!!!
someone help ....

@varungpt
Copy link

varungpt commented Sep 1, 2018

@kishan2212 I was getting the same error, the problem was I was not calling addFriendDialog.setTargetFragment(this, 0);, passing the calling fragment in the Dialog solved the problem.

@leocarona
Copy link

leocarona commented Dec 5, 2018

The following also seems to work

callback = (OnAddFriendListener) getFragmentManager().getFragments().get(0)

Though I'm not sure how much recommended solutions like this are. Perhaps @varungpt solution is better practice?

@t-bad
Copy link

t-bad commented Dec 10, 2018

i got same error as @kishan2212 and any solutions above dont help me...

@anscharivs
Copy link

I spent the whole afternoon looking for this code. THANKS A LOT.

@mucsirobert
Copy link

This is still useful. Very good job man!!! Thank you very much!

@olalekan-oloba
Copy link

Cool

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment