Question

I have an alert box with an EditText.
It doesn't go through the "if" when I try to compare it to the user input.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    alert.setTitle("Number of players: ");


     final EditText input = new EditText(this);
    alert.setView(input);

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {

        }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            // Canceled.
        }
    });

    alert.show();

it doesn't work from here on:

String newString = input.getText().toString();

if(newString.equals("2"))

    {
        System.out.print("lol");

    }

Thanks for any help!

Était-ce utile?

La solution

You have to put the code of your second listing in the OnClickListener of one of your buttons (I guess you want it to be executed after the Ok button is pressed):

...
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        String newString = input.getText().toString();
        if(newString.equals("2")) {
            System.out.print("lol");
        }
    }
});
...

You cannot expect to get the user input immediately after the dialog is shown. The user simply does not have time to type anything.

Autres conseils

I am sure the if is working correctly, you just don't see it. Using System.out.print(); in an android application is not advisable since there is no console to output to. Use Logcat instead.

More info on the topic

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top