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.
Weak but speedy solution:
Declare an Activity level method:
and call it from positive button click listner:
You can change lblDiaDestination value just before alert.show():
You can follow the Dialog tutorial in developer.android.com.
First create dialog class:
Adding a list
Then add listener to this class to pass result to the activity.
Passing Events Back to the Dialog's Host
Variable result , make it a member variable , instead of local variable. By making "result" as member variable it is accessible in the entire activity.(parent class which extends activity)
Simplified example:
-- EDIT -- Or you try this code:
This quite long. I hope my contribution could be useful for the the new comers. I think the key to answer the question is declaring the variable result as member of the activity (let's call it YourActivity). Then from inside the "onClick" method, use YourActivity.this.result to access this variable.
I edit @finiteloop codes as below: