G Ganesh
G Ganesh

Reputation: 99

how to receive the data from dialog fragment to activity in android

I am calling a DialogFragment from Activity to select the state (RecyclerView in DialogFragment).
But i'm not sure how to receive back the selected state.
I know use of Recyclerview, the main task is send back data to previous activity from DialogFragment.
From Activity to Activity I can use startActivityForResult(intent, code) , but from Activity to DialogFragment i'm not getting this.

Activity1 ---> DialogFragment ---> Activity1

Can anyone help me. Thanks in advance.

Upvotes: 0

Views: 233

Answers (2)

Mohsen HZ
Mohsen HZ

Reputation: 29

you can use interface an call it in your activity

public interface OnChangeListener { void onChange(int state);

}

Upvotes: 1

Ghulam Qadir
Ghulam Qadir

Reputation: 519

The preferred method is to use a callback to get a signal from a Fragment. Also, this is the recommended method proposed by Android at Communicating with the Activity

For your example, in your DialogFragment, add an interface and register it.

public static interface OnCompleteListener {
    public abstract void onComplete(String time);
}

private OnCompleteListener mListener;

// make sure the Activity implemented it
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity); 
    try {
        this.mListener = (OnCompleteListener)activity;
    }
    catch (final ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement OnCompleteListener");
    }
}

Now implement this interface in your Activity

public class MyActivity extends Activity implements MyDialogFragment.OnCompleteListener {
    //...

    public void onComplete(String time) {
        // After the dialog fragment completes, it calls this callback.
        // use the string here
    }
}

Now in your DialogFragment, when a user clicks the OK button, send that value back to the Activity via your callback.

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    String time = Integer.toString(hourOfDay) + " : " + Integer.toString(minute);
    this.mListener.onComplete(time);
}

You can pass selected list values by using cal back in similar way

Upvotes: 1

Related Questions