How to get data from SimpleDialogFragment to a Fragment?

164 views Asked by At

I have a main class:

public class MainFragment extends Fragment implements OnClickListener, OnMarkerClickListener {}

I have a dialog class:

public class PedirTaxiDialog extends SimpleDialogFragment implements
    OnClickListener{}

For example: I have FragmentA from which I start SimpleDialogFragment (there are EditText in box). How to can I get back the value from the EditText to FragmenaA? I try to make many things ... but I have no sucessy. Help me please !!

In my MainFragment class, I show the dialog class:

FragmentActivity activity;
activity = (FragmentActivity) getActivity().new PedirTaxiDialog().show(activity.getSupportFragmentManager(), "Salvar Favoritos");

I would get the values entered by the user in the dialog class. How can I in my MainFragment get the return of PedirTaxiDialog?

links of classes:

PedirTaxiDialog.java

MainFragment.java

2

There are 2 answers

0
Oleg Osipenko On BEST ANSWER

Suppose you have this code where you're creating your dialog

FragmentManager fm = getActivity()
                     .getSupportFragmentManager();
             PedirTaxiDialog dialog = PedirTaxiDialog();
             dialog.setTargetFragment(MainFragment.this, "some request tag");
             dialog.show(fm, "Salvar Favoritos");

By calling method setTargetFragment() you're enabling option to get result from your DialogFragment as you're getting result from activity when you're starting it using startActivityForResult().

So in your DialogFragment when user clicks OK button, in the OnClickListener you have to create intent, put to it as String Extra text user entered, set Result_OK and call getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, yourIntent) like this:

Intent i = new Intent();
i.putExtra("textInput", text);
i.setResult(Activity.RESULT_OK);
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, i);

And then in your MainFragment override onActivityResult() method:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK && requestCode == "some request tag") {
        String text = getStringExtra("textInput);
    }
}
1
Stefan Bangels On

You can access your Activity from your Dialog, if you override the onAttach(Activity) method of your DialogFragment.

For example:

private MainActivity controller;

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    this.controller = (MainActivity) activity;
}

@Override
public void onDetach() {
    this.controller = null;
    super.onDetach();
}

Later, you can use the controller object to invoke methods on your Activity.

Your activity can then update the fragment.

Best practice is also to let your activity implement a callback interface, and use this callback interface as class for the controller variable, instead of using the activity class itself.