Android检查多个字符串是否为空

时间:2016-01-10 15:14:16

标签: java android android-studio

我有一个表单,我将表单数据放在一个intent中,然后启动一个新的活动并发送意图的数据,但我想检查字符串是否为空我应该显示和错误消息。如果字符串不为空,则可以启动活动。

我尝试过以下代码,但似乎没有用。如果该字段为空,则只启动另一个活动 (我现在只尝试了1个字段,因为我不知道如何为多个字段使用它)

    //getting the field values
    String firstname = editTextFirstname.getText().toString();
    String lastname = editTextLastname.getText().toString();
    String amount = editTextBedrag.getText().toString();
    String timespan = spinnerPeriode.getSelectedItem().toString();
    String iban = editTextIBAN.getText().toString();

    if(firstname != null) {
        //putting data in the intent
        intent.putExtra(FIRSTNAME, firstname);
        intent.putExtra(LASTNAME, lastname);
        intent.putExtra(AMOUNT, amount);
        intent.putExtra(TIMESPAN, timespan);
        intent.putExtra(IBAN, iban);

        startActivity(intent);
    }else{
        Toast.makeText(MainActivity.this, "Oops, you forgot to fill in some fields!", Toast.LENGTH_SHORT).show();
    }

6 个答案:

答案 0 :(得分:6)

更简洁的方法是

public static boolean isAnyStringNullOrEmpty(String... strings) {
    for (String s : strings)
        if (s == null || s.isEmpty())
            return true;
    return false;
}

然后你就可以这样称呼它

if (isAnyStringNullOrEmpty(firstname, lastname, amount, timespan, iban)) {
    Toast.makeText(MainActivity.this, "Oops, you forgot to fill in some fields!", Toast.LENGTH_SHORT).show();
} else {

}

答案 1 :(得分:4)

更改

if(firstname != null)

if(!TextUtils.isEmpty(firstname) && !TextUtils.isEmpty(lastname) &&
     !TextUtils.isEmpty(amount) &&!TextUtils.isEmpty(timespan) &&
     !TextUtils.isEmpty(iban))

答案 2 :(得分:0)

if(firstname != null && lastname != null && amount != null && timespan != null
 && iban != null & firstname.trim().isEmpty() && !lastname.trim().isEmpty() &&
 !amount .trim().isEmpty() && !timespan.trim().isEmpty() && !iban.trim().isEmpty())

答案 3 :(得分:0)

Java 8 + Apache Commons Lang仅限:

String firstname = editTextFirstname.getText().toString();
String lastname = editTextLastname.getText().toString();
String amount = editTextBedrag.getText().toString();
String timespan = spinnerPeriode.getSelectedItem().toString();
String iban = editTextIBAN.getText().toString();


boolean valid =  Stream.of(firstname, lastname, amount, timespan, iban)
                       .allMatch(StringUtils::isNotBlank);

答案 4 :(得分:0)

使用apache commons,我们可以这样做:

boolean valid = StringUtils.isNoneEmpty(firstname, lastname, amount, timespan, iban)

答案 5 :(得分:0)

使用Java Stream API:

private boolean anyBlank(String...strings) {
   return Stream.of(strings).anyMatch(string -> isBlank(string));
}