AlertDialog in if-stetement doesn't show()

Posted by Steffen Kern on Stack Overflow See other posts from Stack Overflow or by Steffen Kern
Published on 2014-08-19T22:18:05Z Indexed on 2014/08/19 22:20 UTC
Read the original article Hit count: 536

Filed under:
|
|

I have the following code:

   public void button_login(View view) {

    // Instantiate an AlertDialog.Builder with its constructor
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) { /* User clicked OK button */ }
    });

    // Preserve EditText values.
    EditText ET_username = (EditText) findViewById(R.id.username);
    EditText ET_password = (EditText) findViewById(R.id.password);

    String str_username = ET_username.toString();
    String str_password = ET_password.toString();

    // Intercept missing username and password.

    if(str_username.length() == 0) {
        builder.setMessage(R.string.hint_username_empty);
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    }

I have an activity that includes the two EditText-Views and a button. When I click the button the shown method will be called.

My problem: The AlertDialog doesnt show up!

When I put the create and show at beginning like this:

 // Instantiate an AlertDialog.Builder with its constructor
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) { /* User clicked OK button */ }
    });
    builder.setMessage(R.string.hint_username_empty);
    AlertDialog dialog = builder.create();
    dialog.show();
    // Preserve EditText values.
    EditText ET_username = (EditText) findViewById(R.id.username);
    EditText ET_password = (EditText) findViewById(R.id.password);

    String str_username = ET_username.toString();
    String str_password = ET_password.toString();

    // Intercept missing username and password.

    if(str_username.length() == 0) {

    }
    }

Then the Dialog shows up.

Any ideas why the dialog doesnt show up in the first place?

Greetz, Steffen

© Stack Overflow or respective owner

Related posts about android

Related posts about show