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 2nd else-if statement and not the third.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText password = (EditText) findViewById(R.id.editText_Password);
Button enter = (Button) findViewById(R.id.button);
enter.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String user_pass;
user_pass = password.getText().toString();
if (user_pass.equals("123")) {
Toast.makeText(MainActivity.this, "Welcome!", Toast.LENGTH_SHORT).show();
Intent I = new Intent("com.mavenmaverick.password.OKActivity");
startActivity(I);
}
else
if(user_pass != "123"){
Toast.makeText(MainActivity.this, "Incorrect", Toast.LENGTH_SHORT).show();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
dialogBuilder.setIcon(R.drawable.ic_launcher);
dialogBuilder.setTitle("Oops!");
dialogBuilder.setMessage("Incorrect Password");
dialogBuilder.setPositiveButton("OK", null);
dialogBuilder.show();
}
else
if (user_pass.isEmpty()) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
dialogBuilder.setIcon(R.drawable.ic_launcher);
dialogBuilder.setTitle("Oops!");
dialogBuilder.setMessage("Password Field Cannot Be Empty");
dialogBuilder.setPositiveButton("OK", null);
dialogBuilder.show();
}
}
});
}
Wrong String comparison with operators. For string comparison, you can use
.equals()
method.By the way for your case,
just use,
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:Your second if checks for
user_pass != "123"
. Logically, if theuser_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.if(user_pass != "123"){
You are checking directly the memoy position, which is always false.
Use if(!user_pass.equals("123")){ instead of.