Returning from a dialog or activity with result

38,959

Solution 1

In a dialog, if you expect a result, you should use callback methods which can are executed when you click on the dialog's buttons.

For example:

AlertDialog.Builder builder = new AlertDialog.Builder(getDialogContext());
builder.setMessage("Message");
builder.setPositiveButton("Yes", new Dialog.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) { 
        Toast.makeText(this, "Yes", Toast.LENGTH_SHORT).show();
        dialog.cancel();
    }

});

builder.setNegativeButton("No", new Dialog.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(this, "No", Toast.LENGTH_SHORT).show();
        dialog.cancel();

    }

});

builder.show();

This way, onClick method will not execute when you run the code, but it will execute when any of your buttons inside the dialog are tapped.

Solution 2

You can use onActivityResult also
In your main activity call
startActivityForResult(intent, 1); //here 1 is the request code

In your Dialog class

Intent intent = new Intent();
intent.putExtra(....) //add data if you need to pass something
setResult(2,intent); //Here 2 result code

so your main activity

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode == 2 && requestCode ==1){
    //do something
}else{
    //do something else
}
}

Solution 3

I use a callback in my Dialog to return some String or Value that the user selected.

i.e. implement an interface in your Dialog

Solution 4

Try giving the dialog a button, implementing an onClickListener with a method call to something in your activity. The code in said method will only be run when the button is clicked, so you'd want to call that method with a different parameter for the buttons, depending on what they did.

Solution 5

For those who are interrested in a way to implement a dialog box to get a result, but without using onActivityResult here is an example using callbacks. This way you can call this custom dialog box from anywhere and do something according to the choice.

A SHORT WAY

public void getDialog(Context context, String title, String body, 

    DialogInterface.OnClickListener listener){

        AlertDialog.Builder ab = new AlertDialog.Builder(context);
        ab
                .setTitle(title)
                .setMessage(body)
                .setPositiveButton("Yes", listener)
                .setNegativeButton("Cancel", listener)
        ;//.show();

        Dialog d=ab.create();
        d.setCanceledOnTouchOutside(false);

        d.show();
    }

    private void showDialog(){
        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                    case DialogInterface.BUTTON_POSITIVE:
                        //DO
                        break;

                    case DialogInterface.BUTTON_NEGATIVE:
                        //DO
                        break;
                }
            }
        };

        getDialog(
                this,
                "Delete",
                "Are you sure to delete the file?",
                dialogClickListener
        );

    }

Another way, suitable if you have to implement different variations of dialog boxes since you can define the all the actions in a single place.

MyDialog.java

public class MyDialog{

    public void deleteDialog(Context context){
        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                    case DialogInterface.BUTTON_POSITIVE:
                        if(listener!=null)
                            listener.onDeleteDialogResponse(true);
                        break;

                    case DialogInterface.BUTTON_NEGATIVE:
                        if(listener!=null)
                            listener.onDeleteDialogResponse(false);
                        break;
                }
            }
        };

        AlertDialog.Builder ab = new AlertDialog.Builder(context);
        ab.setMessage("Are you sure to delete?")
                .setPositiveButton("Yes", dialogClickListener)
                .setNegativeButton("Cancel", dialogClickListener)
                .show();


    }

/** my listner */
    public interface MyDialogListener{
        public void onDeleteDialogResponse(boolean respononse);
    }
    private MyDialogListener listener;

    public void setListener(MyDialogListener listener) {
        this.listener = listener;
    }

}

Use it like this

private void showDialog(){        
        MyDialog dialog=new MyDialog();
        dialog.setListener(new MyDialog.MyDialogListener() {
            @Override
            public void onDeleteDialogResponse(boolean respononse) {
                if(respononse){
                    //toastMe("yessss");
                    //DO SOMETHING IF YES
                }else{
                    //toastMe("noooh");
                    //DO SOMETHING IF NO
                }
            }
        });

            dialog.deleteDialog(this);
}
Share:
38,959
zidarsk8
Author by

zidarsk8

Your average CS student.

Updated on July 09, 2022

Comments

  • zidarsk8
    zidarsk8 almost 2 years

    I would like to know if I can freeze the current Activity, while I wait for another activity or dialog (any would do) to finish.

    I know I can start an activity for results, and handle those there, but the code after startActivityForResult() will still get executed

    this is something I would like to do:

    PopupDialog dialog = new PopupDialog(this,android.R.style.Theme_Black_NoTitleBar);
    dialog.show();
    // wait here, and continue the code after the dialog has finishes
    int result = getResultFromDialogSomehow();
    if (result == 1){
        //do something
    }else{
        //do something else
    }
    

    I know this must sound quite weird, but but I would really appreciate it if anyone can tell me how to achieve such functionality.

  • zidarsk8
    zidarsk8 over 12 years
    the simpelest way of putting it would be that I would like to get something like this int resultCode = showCustomDialog(). I know I can get results from a dialog, but I don't if it is possible to return them like this, cause it would make a lot of code look much nicer.
  • zidarsk8
    zidarsk8 over 12 years
    Thank you, and this is the normal way of using this. But this sort of breaks up the code. And my question is, could I call an activity, and get the result in the same function, and continue with the work. See my comment to the previous answer.
  • Menion Asamm
    Menion Asamm over 12 years
    hmm I probably understand. You want to same behavior as is classic J2SE right? I'm worried this is not possible in android. I really suggest way that wrote Labeeb P or with some custom dialog that will extend android.app.Dialog and some interface that will handle all return possibility
  • Swato
    Swato over 11 years
    Where do you see a setResult method in a dialog?
  • Labeeb Panampullan
    Labeeb Panampullan over 11 years
    you can cast you getContext() to Activity, ((Activity) getContext()).setResult(2,intent);;
  • Mr.Cool
    Mr.Cool about 11 years
    @zidarsk8 i also facing same problem now do you found any solution for this
  • Roger Huang
    Roger Huang over 8 years