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"));

7 comments:

Daniel B.Boakye said...

Do you have to register anything in the manifest?

adil said...

No, no need to register anything in the manifest for local broadcasts.

Unknown said...

I am using 2 spinners on the dialog , when i press 'ok' the value of these spinners should be passed back to the main activity.

the challenge is how do i read the values of spinners ? i dont see any findViewById in AlertDialog

adil said...

Vivek, your question (how to obtain the value in a Spinner in an AlertDialog) is off topic from this post. Please post your question on a programmer forum like Stack Overflow.

Unknown said...

its only taking back us to calling activity ...but how to send data from dialog fragment to the activity?

adil said...

Omkar, which activity do you want to send data to if not the calling activity??

Unknown said...

Thank you brother. It is help me.