3

I want to create a DialogAlert with two buttons 'YES' and 'NO'. I want to capture the result of the Dialog in a boolean variable. Suppose the user clicks the 'YES' button then the DialogResult Should return a true Value and if the user clicks the 'NO' button then the DialogResult should return a False value. Please help me out in doing this. Thanks in advance.

ajay_whiz
  • 17,573
  • 4
  • 36
  • 44
Prachi
  • 994
  • 5
  • 23
  • 36
  • 1
    Possible duplicate of [Adding positive / negative Button to DialogFragment's Dialog](https://stackoverflow.com/questions/18601049/adding-positive-negative-button-to-dialogfragments-dialog) – Riot Goes Woof Jun 03 '19 at 15:49

2 Answers2

4

I would use a AlertDialog (see documentation here). If you have your own class DialogResult the the code could look something like this:

DialogResult result = new DialogResult(); 
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
   .setCancelable(false)
   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            // User clicked Yes: set the value to your result class here. E.g:
            MyActivity.result.setValue(true);
       }
   })
   .setNegativeButton("No", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            // User clicked No: set the value to your result class here. E.g: 
            MyActivity.result.setValue(false);
       }
   });
AlertDialog alert = builder.create();
Kristian
  • 6,357
  • 4
  • 36
  • 37
  • I tried implementing this code but it's giving an error that..'Unable to resolve DialogResult class'. – Prachi May 10 '11 at 10:08
3

Try this code

boolean result;
AlertDialog.Builder invalid_input_dialog = new AlertDialog.Builder(Select_party_foods1.this);
          invalid_input_dialog.setTitle("Event Organise")
          .setMessage(dialog_message)
          .setCancelable(true)
          .setPositiveButton("Ok", new DialogInterface.OnClickListener(){
              @Override
                public void onClick(DialogInterface dialog, int which) {
                 result=true;
                System.out.println("The result is "+result);
              }
          })
          .setNegativeButton("No", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                result=false;
                System.out.println("The result is "+result);                        
            }

          })
          .show();
Jaydeep Khamar
  • 5,975
  • 3
  • 32
  • 30
  • Hi Jaydeep!! Actually I want to get the variable outside this method. I am calling the ShowAlert("Message") in the main method and I want the ShowAlert("Message") to return the boolean result on the basis of the button selected. – Prachi May 10 '11 at 10:03