title: Android : Evaluate Dialog
body: <p>I want to evaluate a Dialog under Android.
  My problem is that the Dialog does not wait
  with returning a value until I pressed a
  button. And when I use a Semaphore the 
  program hangs at Semaphore.acquire().
  Why does it hang at Semaphore.acquire()?</p>
  
  <p>Can you see where I go wrong?</p>
  
  <p>Here is the main activity</p>
  
  <pre><code>package com.example.modaldialog;
  
  import android.app.Activity;
  import android.os.Bundle;
  import android.widget.Toast;
  
  public class MainActivity extends Activity {
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
  
          mDialog meinDialog = new mDialog(this);
          if (meinDialog.ShowMyModalDialog() == 1)
              Toast.makeText(this, "Pressed Button 1",
              Toast.LENGTH_LONG).show();  
      }
  }
  </code></pre>
  
  <p>and here the dialog class</p>
  
  <pre><code>package com.example.modaldialog;
  
  import android.app.AlertDialog;
  import android.content.DialogInterface;
  import android.widget.Toast;
  
  import java.util.concurrent.Semaphore;
  import android.app.Activity;
  import java.lang.Runnable;
  
  public class mDialog
  {
      int pressedButtonID;
      Activity act;
      private final Semaphore dialogSemaphore;    
  
      mDialog(Activity act_in) 
      {
          act = act_in;
          dialogSemaphore = new Semaphore(0, true);
      };
  
      final Runnable mMyDialog = new Runnable()
      {
          public void run()
          {
              AlertDialog errorDialog = new 
                  AlertDialog.Builder(act).create();
              errorDialog.setMessage("Press a Button!");
              errorDialog.setButton("Button2", new   
                  DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      pressedButtonID = 2;
                      dialogSemaphore.release();
                      }
                  });
              errorDialog.setButton2("Button1", new 
                  DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      pressedButtonID = 1;
                      dialogSemaphore.release();
                      }
                  });
              errorDialog.setCancelable(false);
              errorDialog.show();
          }
      };
  
      public int ShowMyModalDialog()  //should be called from non-UI thread
      {
          pressedButtonID = 0;
          act.runOnUiThread(mMyDialog);
          try
          {
              dialogSemaphore.acquire();
          }
          catch (InterruptedException e)
          {
          }
          return(pressedButtonID);
      }
  }
  </code></pre>