为什么赢得这个简单的If语句检查所有条件

时间:2015-04-15 17:04:22

标签: android if-statement android-edittext

我有一个if语句,我想检查所有EditTexts都不为空。我知道这很简单但我无法看到问题。

     if (name.getText().length()<0 & postalcode.getText().length()<0 & phonenumber.getText().length()<0 & age.getText().length()<0 & staffid.getText().length()<0 & password.getText().length()<0) {
        Toast.makeText(getBaseContext(), "No Empty Fields", Toast.LENGTH_LONG).show(); //alerts user that entry has been saved
    } else {
        database1.insertContact(name.getText().toString(), postalcode.getText().toString(), phonenumber.getText().toString(), age.getText().toString(), staffid.getText().toString(), password.getText().toString());

        Toast.makeText(getBaseContext(), "Entry saved :)", Toast.LENGTH_LONG).show(); //alerts user that entry has been saved

        //Intent to go back home
        Intent showContent = new Intent(getBaseContext(), login.class);
        startActivity(showContent);
    }   

2 个答案:

答案 0 :(得分:2)

你应该使用= 0而不是&lt; 0?我不熟悉android语言,但我认为空白文本的长度通常为0而不是-1。

答案 1 :(得分:1)

即使一个人是空的也不对。所以使用和运算符是不正确的

  if (name.getText().length()==0 || postalcode.getText().length()==0 || phonenumber.getText().length()==0 || age.getText().length()==0 || staffid.getText().length()==0 || password.getText().length()==0) {
            Toast.makeText(getBaseContext(), "No Empty Fields", Toast.LENGTH_LONG).show(); //alerts user that entry has been saved

如果所有edittexts都为空,则使用和不会起作用,它只会说edittext为空!您需要使用或以上述方式