Leo Leo - 10 months ago 136
Android Question

Return result to Activity from DialogFragment

I am trying to do the following:

  1. Show dialog fragment from an Activity (not Fragment);

  2. Retrieve result in the Activity.

The problem is that onActivityResult in the Activity is not being called.

Here is how I am showing a DialogFragment

DriverRatingDialogFragment dp = new DriverRatingDialogFragment();
// this solution works well in case of showing dialog from a fragment
// but I have to show it from the Activity
// dp.setTargetFragment(getSupportFragmentManager().findFragmentById(R.id.flContent), DriverRatingDialogFragment.REQUEST_CODE);
dp.show(getSupportFragmentManager(), DriverRatingDialogFragment.ARG_RATING);

And here is how I am trying to return result from DialogFragment:

Intent intent = new Intent();

// This solution works well in case of previously setting target Fragment,
// but I have to return result to Activity

// getTargetFragment().onActivityResult(
// getTargetRequestCode(), REQUEST_CODE, intent);

// and with this attempt App crashes
// this.onActivityResult(REQUEST_CODE, Activity.RESULT_OK, intent);

here is where I want to retrieve result in the Activity, but it doesn't get called:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DriverRatingDialogFragment.REQUEST_CODE) {
// todo

super.onActivityResult(requestCode, resultCode, data);

What's wrong?


I start the DialogFragment the same way you do.

CreatePostDialog createPostDialog = new CreatePostDialog();
createPostDialog.show(getSupportFragmentManager(), "create_post_dialog");

And I send back data using a public method in the activity rather than with intents.


The snippets above are copy pasted examples of my working code. Logout in this case is a public method in MainActivity that takes in a point and does what is needs with it.