繁体   English   中英

检查字符串是否为空或空 - 逻辑

[英]check string is null or empty - logic

在这篇文章的延续( 检查字符串是 NULL 或 EMPTY ),我成功地写出了 if 和 else 逻辑。

但是,我的第三个逻辑不起作用。 我的第三个逻辑类似于同时检查两个空字段,如果它们为空,则会弹出错误图标。

以下是我的代码:

    private Boolean checkEmptyField(){
    Boolean result = false;

    String subject = querySubject.getText().toString();
    String message = queryText.getText().toString();

    if(subject.isEmpty()){
        Toast.makeText(this, "Subject/Type field must not be blank!", Toast.LENGTH_SHORT).show();
        querySubjectInfoIcon.setVisibility(View.VISIBLE);
    }else if(message.isEmpty()){
        Toast.makeText(this, "Content field must not be blank!", Toast.LENGTH_SHORT).show();
        newQueryInfoIcon.setVisibility(View.VISIBLE);
    }else if(subject.isEmpty() && message.isEmpty()){
        Toast.makeText(this, "Fields are mandatory & must not be blank!", Toast.LENGTH_SHORT).show();
        newQueryInfoIcon.setVisibility(View.VISIBLE);
        querySubjectInfoIcon.setVisibility(View.VISIBLE);
    }
    else{
        result = true;
    }
    return result;
}

当我运行该应用程序并有意将两个字段留空时,它只会检查并在作为主题字段的一个字段上显示图标错误。 这意味着只有一个逻辑(if subject.isEmpty)正在运行。

因此,我需要一些建议如何成功运行第三个逻辑。 谢谢你。

首先对两个条件进行测试,一旦if匹配,它将不会输入任何else (s)。 喜欢,

if(subject.isEmpty() && message.isEmpty()) {
    Toast.makeText(this, "Fields are mandatory & must not be blank!", Toast.LENGTH_SHORT).show();
    newQueryInfoIcon.setVisibility(View.VISIBLE);
    querySubjectInfoIcon.setVisibility(View.VISIBLE);
} else if(subject.isEmpty()) {
    Toast.makeText(this, "Subject/Type field must not be blank!", Toast.LENGTH_SHORT).show();
    querySubjectInfoIcon.setVisibility(View.VISIBLE);
} else if(message.isEmpty()) {
    Toast.makeText(this, "Content field must not be blank!", Toast.LENGTH_SHORT).show();
    newQueryInfoIcon.setVisibility(View.VISIBLE);
} else {
    result = true;
}

一旦您的第一个if条件触发,下面的else if就不会触发。 首先在if检查subject.isEmpty() && message.isEmpty() ,然后再检查其他两个条件。

  • 你可以用这个检查它:

     if (userName != null && !userName .isEmpty() && !userName .equals("null"))
  • 你还有另一个选择

    if (TextUtils.isEmpty(null)) { // null value return; // or break, continue, throw }else{ // string has value } Log.i("TAG", myString);

用这个

if(subjet == null){
    //blablabla
}

或者

if(message == null){
    //blablabla
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM