How can I get the results from an AlertDialog?

41,789

Solution 1

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();
    }
}

Solution 2

Simplified example:

public interface TextListener {
    void onPositiveResult(CharSequence text);
}

public static AlertDialog getTextDialog(Context ctx,
        final TextListener listener) {
    View view = LayoutInflater.from(ctx).inflate(R.layout.dialog, null);
    final TextView tv = (TextView) view.findViewById(R.id.tv);
    AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
    builder.setView(view);
    //
    builder.setPositiveButton(android.R.string.ok, new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            listener.onPositiveResult(tv.getText());
        }
    });
    builder.setNegativeButton(android.R.string.cancel, null);
    return builder.create();
}

-- EDIT -- Or you try this code:

 public class Main extends Activity {
    private Button btn;
    private String result;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showDialog(0);
            }
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case 0:
            final EditText input = new EditText(this);

            return new AlertDialog.Builder(this)
            .setIcon(R.drawable.icon)
            .setTitle("Please enter a password")
            .setView(input)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int whichButton) {
                    Toast.makeText(getBaseContext(), input.getText().toString(), Toast.LENGTH_SHORT).show();
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int whichButton) {
                    Toast.makeText(getBaseContext(), "Cancel clicked!", Toast.LENGTH_SHORT).show();
                }
            }).create();
        }

        return null;
    }
}

Solution 3

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

Solution 4

Weak but speedy solution:

Declare an Activity level method:

TextView lblDiaDestination;

public void dialogReturn(String msg){
   lblDiaDestination.setText(msg);
}

and call it from positive button click listner:

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        dialogReturn(   input.getText().toString().trim()   );
    });

You can change lblDiaDestination value just before alert.show():

lblDiaDestination = myTextView;
alert.show():

Solution 5

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)

Share:
41,789

Related videos on Youtube

finiteloop
Author by

finiteloop

Front-end developer with a passion for building quality user interfaces. Always keeping a mind on developer ergonomics, and automation to work toward and maintain higher code quality.

Updated on November 24, 2020

Comments

  • finiteloop
    finiteloop over 3 years

    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.

  • finiteloop
    finiteloop about 13 years
    Sorry, I don't quite understand what's going on here, or how I would use this to achieve what I'm trying to achieve.
  • nicholas.hauschild
    nicholas.hauschild about 13 years
    evilone is suggesting you use the Observer pattern and create your own listener (TextListener). Your Activity that is housing this AlertDialog can then implement TextListener which will call onPositiveResult(CharSequence) outside of the AlertDialog, and it will pass in the result that you are looking for based on your question. You can then act on your result as you wish.
  • finiteloop
    finiteloop about 13 years
    +1 for right answer. I chose @Femi's because it was more robust. Thanks!