Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: wait on user input from dialog?

I would like to implement a method that displays a dialog, waits until the dialog is dismissed, and then returns a result depending on the dialog contents. Is this possible?

public String getUserInput() {     //do something to show dialog     String input = //get input from dialog     return input; } 

I am actually trying to implement an interface which has method "public String getUserInput()", where the returned String must be retrieved via dialog. This is easily done in java, seems impossible in android?

EDIT: Posting some sample code as requested in comment

getInput() must be called from a background thread (I call it from an AsynchTask). getInput() displays a dialog and calls wait. When the ok button is pressed on the dialog, the dialog sets the user input in a member variable and calls notify. When notify is called, getInput() continues and returns the member variable.

String m_Input;  public synchronized String getInput() {     runOnUiThread(new Runnable()      {         @Override         public void run()          {             AlertDialog.Builder alert = new AlertDialog.Builder(context);             //customize alert dialog to allow desired input             alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {             public void onClick(DialogInterface dialog, int whichButton)             {                           m_Input = alert.getCustomInput();                           notify();             }         });         alert.show();            }     });      try      {          wait();     }      catch (InterruptedException e)      {     }      return m_Input; } 
like image 514
ab11 Avatar asked Dec 07 '10 20:12

ab11


1 Answers

Is this possible?

No. There is no blocking UI model in Android. Everything is asynchronous.

UPDATE

In response to some of your comments on the question itself, you cannot display a UI from a background thread. As I wrote in this answer, there is no blocking UI model in Android. Just put your code in the button handler for your dialog that you want to have executed when the dialog is accepted, such as in this sample project.

like image 63
CommonsWare Avatar answered Sep 22 '22 06:09

CommonsWare