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 {

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

        if (intent.getAction().equals("SOME_ACTION")) {
           doSomeAction();
        }
    }
}

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:

LocalBroadcastManager.getInstance(this).registerReceiver(
        localBroadcastReceiver,
        new IntentFilter("SOME_ACTION"));

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

LocalBroadcastManager.getInstance(this).unregisterReceiver(
        localBroadcastReceiver);

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

LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(
    new Intent("SOME_ACTION"));