Android Java : How to wait for user input from a dialog.
Have you ever wanted to create a dialog and had the need to wait for
user input from the dialog then resume execution? In Android, this is not possible because
you would be blocking the UI Thread. Instead we can pass a Runnable
to the button events in the
dialog to execute the code after a button is clicked!
Here is a workaround:
1) create an implementation of Runnable
so we can save/retrieve a value from the dialog.
2) create a function that produces the dialog and accepts our PromptRunnable
code.
3) call that function when we need to prompt for input and pass our PromptRunnable
that
needs to run after the dialog has captured input.
Create our own implementation of Runnable
so we can get/set the value from the dialog:
Alternately, create your own interface instead of using the Runnable
interface.
See Wait for User Input from Dialog - Alternate Solution for an
example of how to specify your own interface.
1. 2. 3. 4. 5. 6. 7. 8. 9. 10.
11. 12.
|
|
class PromptRunnable implements Runnable {
private String v;
void setValue(String inV) {
this.v = inV;
}
String getValue() {
return this.v;
}
public void run() {
this.run();
}
} |
Function to create our dialog:
1. 2. 3. 4. 5. 6. 7. 8. 9. 10.
11. 12. 13. 14. 15. 16. 17. 18. 19. 20.
21. 22. 23. 24. 25. 26. 27. 28. 29. 30.
|
|
void promptForResult(final PromptRunnable postrun) {
Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Title");
alert.setMessage("Message.");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
dialog.dismiss();
postrun.setValue(value);
postrun.run();
return;
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
return;
}
});
alert.show();
}
|
Pass our PromptRunnable
to promptForResult() where you need to prompt for input:
1. 2. 3. 4. 5. 6. 7. 8. 9. 10.
11. 12. 13.
|
|
promptForResult(new PromptRunnable(){
public void run() {
String value = this.getValue();
Intent i = new Intent(getApplication(), MyActivity.class);
i.putExtra("extraValue", value);
startActivity(i);
}
});
|
This example code doesn't wait for user input, instead we are passing code to be run after
the user hits the "Ok" button on the dialog. Alternately, create a custom listener interface instead of using
the Runnable
interface.
See Wait for User Input from Dialog - Alternate Solution for an
example of how to specify your own interface.
Published by: Thomas Penwell
Initially published on: August 7, 2012
Article last modified on: Saturday, November 1, 2014.