Returning from a dialog or activity with result

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


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.


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
}
}