Ad

How Process Result From Alert Dialog? (Android)

- 1 answer

I'm working on a small class which can generate Alert dialog boxes. The constructor of the class looks like this:

void popupMessage(String title, String message, String pText, String nText, boolean cancelable) {
        setPopupResult(999);
        AlertDialog.Builder dialog = new AlertDialog.Builder(currentActivity);
        dialog.setMessage(message).setCancelable(cancelable);
        dialog.setNegativeButton(nText, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setPopupResult(0);
            }
        });
        dialog.setPositiveButton(pText, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setPopupResult(1);
            }
        });

        AlertDialog alert = dialog.create();
        alert.setTitle(title);
        alert.show();
    }

as you see based on pressing the yes or no button the code sets the value of a private variable to 0 or 1 which can be accessed by a getter method. (the value is set to 999 at the top, this indicates that the user did no press anything yet)

The problem I'm facing is that from in the calling activity I somehow should be able to capture when the popupResult variable changes from 999 to either 0 or 1. How can I do that?

(I could be wrong handling the Alert dialog like this, feel free to educate me)

Ad

Answer

Since the user's clicking on your dialog buttons is asynchronous to when you're showing the dialog, one way to do it, would be to provide some kind of callback to your method, that is called when the buttons are clicked.

Example:

/* define this inside your dialog class */
public interface Callback {
    void onOkClicked();
    void onCancelClicked();
}

void popupMessage(String title, String message, String pText, String nText, boolean cancelable, Callback callback) {
    ...
        /* positive button clicklistener, for negative button, use callback.onCancelClicked() */
        public void onClick(DialogInterface dialog, int which) {
            callback.onOKClicked();
        }
    ... 
}

/* Using the method */
popupMessage(..., new Callback() {
    void onOKClicked() {
        /* do something when OK was clicked */
    }

    void onCancelClicked() {
        /* do something when Cancel was clicked */
    }
});   
Ad
source: stackoverflow.com
Ad