Sunday, 4 October 2015

Android - how to pass data from DialogFragment to Activity

So you've started a DialogFragment from within an Activity and want to request an action or pass data from the DialogFragment to the Activity. The best, cleanest way I find to do so is by means of local broadcasts. Here's how...

First, define a BroadcastReceiver in your Activity as follows:

private class LocalBroadcastReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        // safety check
        if (intent == null || intent.getAction() == null) {

        if (intent.getAction().equals("SOME_ACTION")) {

Second, declare an instance of LocalBroadcastReceiver in your Activity, as follows:

private BroadcastReceiver localBroadcastReceiver;

Third, instantiate the BroadcastReceiver in the activity's onCreate(Bundle) method:

localBroadcastReceiver = new LocalBroadcastReceiver();

Fourth, register for the activity to listen out for the local broadcasts in the activity's onResume() method:

        new IntentFilter("SOME_ACTION"));

Fifth, unregister the broadcast receiver in the activity's onPause() method:


Sixth and final, send the broadcast from wherever makes sense in your DialogFragment, as follows:

    new Intent("SOME_ACTION"));