user3502368
user3502368

Reputation:

Android confirm dialog dont wait for the user

I have that code here:

 int flagconfirm;

      public void resultado(View v)
     {
     warning();

     if(flagconfirm==0)
     return;

     finish();
     }

public void warning()
    {
        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
            @Override

            public void onClick(DialogInterface dialog, int which) {

                int flag=0;
                switch (which){
                    case DialogInterface.BUTTON_POSITIVE:
                        flagconfirm=1;
                        break;

                    case DialogInterface.BUTTON_NEGATIVE:
                        return;
                }
            }

        };
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Exit?").setPositiveButton("Yes", dialogClickListener)
                .setNegativeButton("No", dialogClickListener).show();

    }

But the problem is the compiler call the function and continue the work, it don't wait for the answer of the user. So i need to click the button 2 times, and accept 2 times. Can anyone help me?Thanks.

Upvotes: 0

Views: 166

Answers (1)

Marius
Marius

Reputation: 820

Waiting for user Input is done asynchronously, so, when you create and show your AlertDialog, rest of the method body continues execution. You have to either stop the execution(BAD when on GUI thread, which is the case now), or call some method from the listener. Modify your structure to something like this:

public void resultado(View v) {
    warning();
}

dialogClickListener = ...{
    int flag=0;
            switch (which){
                case DialogInterface.BUTTON_POSITIVE:
                    parsePositive();
                    break;

                case DialogInterface.BUTTON_NEGATIVE:
                    parseNegative(dialog); 
                    return;
            }  }

void parsePositive(){finish();}
void parseNegative(DialogInterface dialog){dialog.dismiss();}

Upvotes: 1

Related Questions