How to get DialogResult in android?

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, and then DialogResult should return the true value, and if the user clicks the NO button, then DialogResult should return False. Please help me with this. Thanks in advance.

+3
source share
2 answers

I would use AlertDialog ( see documentation here ). If you have your own DialogResult class, the code might 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();
+4
source

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();
+3
source

All Articles