Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AlertDialog in a function which has a return value

I have written a function which has a return value of type int,and in this function I need to pop up an AlertDialog with two buttons. When the "Yes" button is clicked,the function return 0,and "No" button return -1.

public int Func(){
    final AlertDialog d=new AlertDialog.Builder(mContext).setTitle("Warning").setCancelable(false).setMessage
                       (alert)
                       .setPositiveButton("Yes",mListener).setNegativeButton("No",mListener).create();
                       d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                       d.show();
   if(mWhich.getWhich()==-1)   //the "yes" button was clicked
       return 0;
   else                        //the "no"  button was clicked
       return -1;
}

mWhich is a class used to record the user choices

private DialogInterface.OnClickListener mListener =
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    mWhich.setWhich(which);
                             }
            };

Now the problem is the code

if(mWhich.getWhich()==-1)
       return 0;
   else
       return -1;

was executed before the user click the yes or no button,how should I do??

like image 705
Caroline Avatar asked Nov 03 '22 09:11

Caroline


1 Answers

As I understood, your code looks similar to

// some code
int result = Func();
DoSmthWithResult(result);
// some code

Your Func is running on the UI thread, so after you create dialog it continues executing and returns initial value of mWich. You should call DoSmthWithResult from onClickListener instead:

private DialogInterface.OnClickListener mListener = new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        DoSmthWithresult(which == -1 ? 0 : -1);
    }
};

Now DoSmthWithResult will be executed after user pressed "yes" or "no" button.

like image 103
Yury Pogrebnyak Avatar answered Nov 11 '22 09:11

Yury Pogrebnyak