Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the results from an AlertDialog?

Tags:

I am using an AlertDialog.Builder to display a dialog to prompt the user to enter a password, I then want to save that password in a preference, however I can't figure out how to get the result from the alert dialog's input method.

Here is essentially what I would like to be able to do:

    String result;     AlertDialog.Builder b = new AlertDialog.Builder(this);     b.setTitle("Please enter a password");     final EditText input = new EditText(this);     b.setView(input);     b.setPositiveButton("OK", new DialogInterface.OnClickListener()     {         @Override         public void onClick(DialogInterface dialog, int whichButton)         {            //I get a compile error here, it wants result to be final.            result = input.getText().toString();         }     });     b.setNegativeButton("CANCEL", null);     b.create().show(); 

However, I am open to doing something such as showDialog(int); then using the onCreateDialog(int) method and somehow setting the result and receiving it in some other method, but I have no idea how to go about the last part.

like image 913
finiteloop Avatar asked May 10 '11 17:05

finiteloop


People also ask

How do I get view from AlertDialog?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

What is AlertDialog message?

AlertDialog. A dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout. DatePickerDialog or TimePickerDialog. A dialog with a pre-defined UI that allows the user to select a date or time.

What is the difference between dialog and AlertDialog?

AlertDialog is a lightweight version of a Dialog. This is supposed to deal with INFORMATIVE matters only, That's the reason why complex interactions with the user are limited. Dialog on the other hand is able to do even more complex things .

Which method is used to set in AlertDialog?

The way to make a checkbox list is to use setMultiChoiceItems . // setup the alert builder AlertDialog. Builder builder = new AlertDialog. Builder(context); builder.


1 Answers

public class MyActivity extends Activity {     private String result;      void showDialog() {         AlertDialog.Builder b = new AlertDialog.Builder(this);         b.setTitle("Please enter a password");         final EditText input = new EditText(this);         b.setView(input);         b.setPositiveButton("OK", new DialogInterface.OnClickListener() {             @Override             public void onClick(DialogInterface dialog, int whichButton) {                 result = input.getText().toString();             }         });         b.setNegativeButton("CANCEL", null);         b.show();     } } 
like image 108
Femi Avatar answered Sep 26 '22 02:09

Femi