Skip to content Skip to sidebar Skip to footer

Checking If Edittext.isempty() Not Working

In my code, I want to check if the password field is empty. I am using the isEmpty() method to accomplish it but it does not work. Leaving the password field blank, reverts to the

Solution 1:

if (string == "aString") {
    ...
} elseif (string != "somestring") {
    ...
} elseif (string.isEmpty()) {
    ...
}

This won't check if the string is empty, it will stop on the 2nd if block since it's not equal.

To avoid this, check if it's empty first. Also don't use == when comparing string values:

if (user_pass.isEmpty()) {
    // It's empty
} elseif (user_pass.equals("123")) {
    // Equals
} elseif (!user_pass.equals("123")){
    // Not equals
}

Solution 2:

Wrong String comparison with operators. For string comparison, you can use .equals() method.

By the way for your case,

just use,

if (user_pass.isEmpty()) {
      displayAlertDialog("Password Field Cannot Be Empty");
}elseif(user_pass.equals("123"))
{
 Toast.makeText(MainActivity.this, "Welcome!", Toast.LENGTH_SHORT).show();
 IntentI=newIntent("com.mavenmaverick.password.OKActivity");
 startActivity(I);

}else
{
Toast.makeText(MainActivity.this, "Incorrect", Toast.LENGTH_SHORT).show();
    displayAlertDialog("Incorrect Password");               
}

privatevoiddisplayAlertDialog(String message)
{
 AlertDialog.BuilderdialogBuilder=newAlertDialog.Builder(MainActivity.this);
                            dialogBuilder.setIcon(R.drawable.ic_launcher);
                            dialogBuilder.setTitle("Oops!");
                            dialogBuilder.setMessage(message);
                            dialogBuilder.setPositiveButton("OK", null);
                            dialogBuilder.show();
}

Solution 3:

if(user_pass != "123"){

You are checking directly the memoy position, which is always false.

Use if(!user_pass.equals("123")){ instead of.

Solution 4:

Your second if checks for user_pass != "123". Logically, if the user_pass is empty it is not "123" and it won't even go for the third if. If you want it to work, switch your second and third if.

Post a Comment for "Checking If Edittext.isempty() Not Working"