Receive Result from Dialogfragment

Receive result from DialogFragment

Use myDialogFragment.setTargetFragment(this, MY_REQUEST_CODE) from the place where you show the dialog, and then when your dialog is finished, from it you can call getTargetFragment().onActivityResult(getTargetRequestCode(), ...), and implement onActivityResult() in the containing fragment.

It seems like an abuse of onActivityResult(), especially as it doesn't involve activities at all. But I've seen it recommended by official google people, and maybe even in the api demos. I think it's what g/setTargetFragment() were added for.

How to get the result from the DialogFragment in Android?

Fragment class:

public class MyFragment extends Fragment {
int mStackLevel = 0;
public static final int DIALOG_FRAGMENT = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

if (savedInstanceState != null) {
mStackLevel = savedInstanceState.getInt("level");
}
}

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("level", mStackLevel);
}

void showDialog(int type) {

mStackLevel++;

FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
Fragment prev = getActivity().getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);

switch (type) {

case DIALOG_FRAGMENT:

DialogFragment dialogFrag = MyDialogFragment.newInstance(123);
dialogFrag.setTargetFragment(this, DIALOG_FRAGMENT);
dialogFrag.show(getFragmentManager().beginTransaction(), "dialog");

break;
}
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case DIALOG_FRAGMENT:

if (resultCode == Activity.RESULT_OK) {
// After Ok code.
} else if (resultCode == Activity.RESULT_CANCELED){
// After Cancel code.
}

break;
}
}
}

}

DialogFragment class:

public class MyDialogFragment extends DialogFragment {

public static MyDialogFragment newInstance(int num){

MyDialogFragment dialogFragment = new MyDialogFragment();
Bundle bundle = new Bundle();
bundle.putInt("num", num);
dialogFragment.setArguments(bundle);

return dialogFragment;

}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

return new AlertDialog.Builder(getActivity())
.setTitle(R.string.ERROR)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, getActivity().getIntent());
}
}
)
.setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, getActivity().getIntent());
}
})
.create();
}
}

I hope it's helpful!

Return result to Activity from DialogFragment

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.

((MainActivity)mContext).logout(Utils.getLocation(v));

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.

How can i get data back from this dialog fragment in this code?

Create a callback interface, implement it on your code (where you set up the listeners), then pass it as a parameter in the dialog.

Example:

public interface Callback {
void onResult(Object result);
}
private Callback callback;
public ListTipo(Callback callback) {
this.callback=callback;
}

// where you want to pass the result
callback.onResult(YOUR_RESULT);

Where you create the dialog:

xTipo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new ListTipo(result -> {
// run your code with result
}).show(getSupportFragmentManager(),"ListTipo");
}
});

How to receive result from a dialog fragment to a dialog fragment

I have solved the issue.I just implemented a interface in dialog B.Checks and initialize interface in onCreate method in dialog A whether the hosting dialog is activity /dialog.

Here is the code

Dialog DialogTwo as A :

public class DialogTwo extends DialogFragment {


@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
if(!(getActivity() instanceof SelectedItemListener)) {
callback = (SelectedItemListener) getTargetFragment();
}
} catch (Exception e) {
throw new ClassCastException("Calling Fragment must implement SelectedItemListener");
}

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AlertDialogCustom));

builder.setTitle(R.string.select_color)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (getActivity() instanceof SelectedItemListener) {
((NewExerciseActivity) getActivity()).manageSelectedItem();
}else {
callback.manageSelectedItem();
}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});

return builder.create();
}
}

Call from Dialog B :

 private void showDialog() {
FragmentActivity activity = (FragmentActivity) getActivity();
FragmentManager fm = activity.getSupportFragmentManager();
DialogTwo dialogTwo = new DialogTwo();
dialogTwo.setTargetFragment(this,0);
dialogTwo.show(fm, "dialogTwo");
}

@Override
public void manageSelectedItem() {
//do something
}

How to receive result from a dialog fragment to a dialog fragment

I have solved the issue.I just implemented a interface in dialog B.Checks and initialize interface in onCreate method in dialog A whether the hosting dialog is activity /dialog.

Here is the code

Dialog DialogTwo as A :

public class DialogTwo extends DialogFragment {


@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
if(!(getActivity() instanceof SelectedItemListener)) {
callback = (SelectedItemListener) getTargetFragment();
}
} catch (Exception e) {
throw new ClassCastException("Calling Fragment must implement SelectedItemListener");
}

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AlertDialogCustom));

builder.setTitle(R.string.select_color)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (getActivity() instanceof SelectedItemListener) {
((NewExerciseActivity) getActivity()).manageSelectedItem();
}else {
callback.manageSelectedItem();
}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});

return builder.create();
}
}

Call from Dialog B :

 private void showDialog() {
FragmentActivity activity = (FragmentActivity) getActivity();
FragmentManager fm = activity.getSupportFragmentManager();
DialogTwo dialogTwo = new DialogTwo();
dialogTwo.setTargetFragment(this,0);
dialogTwo.show(fm, "dialogTwo");
}

@Override
public void manageSelectedItem() {
//do something
}

Get value from DialogFragment

Assuming that you want to foward result to the calling Activity:) try this code snippet:

public class QuantityDialogFragment extends DialogFragment implements OnClickListener {

private EditText editQuantity;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
editQuantity = new EditText(getActivity());
editQuantity.setInputType(InputType.TYPE_CLASS_NUMBER);

return new AlertDialog.Builder(getActivity()).setTitle(R.string.app_name).setMessage("Please Enter Quantity")
.setPositiveButton("OK", this).setNegativeButton("CANCEL", null).setView(editQuantity).create();

}

@Override
public void onClick(DialogInterface dialog, int position) {
String value = editQuantity.getText().toString();
Log.d("Quantity: ", value);
MainActivity callingActivity = (MainActivity) getActivity();
callingActivity.onUserSelectValue(value);
dialog.dismiss();
}
}

and on Your activity add :

public class MainActivity extends FragmentActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QuantityDialogFragment dialog = new QuantityDialogFragment();
dialog.show(getSupportFragmentManager(), "Dialog");
}

/**
* callback method from QuantityDialogFragment, returning the value of user
* input.
*
* @param selectedValue
*/
public void onUserSelectValue(String selectedValue) {
// TODO add your implementation.
}
}

Receive DialogFragment result in BottomSheetDialogFragment

My intention was to open a DialogFragment from a BottomSheetDialogFragment and get a result a bit like a callback.

Despite the fact that a BottomSheetDialogFragment extends AppCompatDialogFragment that extends DialogFragment that extends Fragments, I wasn't able to "setTargetFragment" from BottomSheetDialogFragment. Therefore I decided to change the approach and to use customs listeners. I'm now calling both my BottomSheetDialogFragment and DialogFragment directly from the MainActivity by listening to each of them.

Simple and it works as expected.

How to get data from DialogFragment to a Fragment?

The Fragment.onActivityResult() method is useful in this situation. It takes getTargetRequestCode(), which is a code you set up between fragments so they can be identified. In addition, it takes a request code, normally just 0 if the code worked well, and then an Intent, which you can attach a string too, like so

Intent intent = new Intent();
intent.putExtra("STRING_RESULT", str);

Also, the setTargetFragment(Fragment, requestCode) should be used in the fragment that the result is being sent from to identify it. Overall, you would have code in the requesting fragment that looks like this:

FragmentManager fm = getActivity().getSupportFragmentManager();
DialogFragment dialogFragment = new DialogFragment();
dialogFragment.setTargetFragment(this, REQUEST_CODE);
dialogFragment.show();

The class to send data (the DialogFragment) would use this Fragment we just defined to send the data:

private void sendResult(int REQUEST_CODE) {
Intent intent = new Intent();
intent.putStringExtra(EDIT_TEXT_BUNDLE_KEY, editTextString);
getTargetFragment().onActivityResult(
getTargetRequestCode(), REQUEST_CODE, intent);
}

To receive the data, we use this type of class in the Fragment which initially started the DialogFragment:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Make sure fragment codes match up
if (requestCode == DialogFragment.REQUEST_CODE) {
String editTextString = data.getStringExtra(
DialogFragment.EDIT_TEXT_BUNDLE_KEY);

At this point, you have the string from your EditText from the DialogFragment in the parent fragment. Just use the sendResult(int) method in your TextChangeListener() anonymous class so that the text is sent when you need it.



Related Topics



Leave a reply



Submit