如何给 java 中的 CharSequence 赋空值?
How to assign null value to CharSequence in java?
在我的应用程序中,我使用的是 EditText。当编辑文本中没有文本时,我想分配 numberOfYearsBirthday=0。
下面的代码我已经试过并调试过了。我已经看到,即使我的 charSequence="" 但它会忽略该语句并移动到 else 语句,从而导致错误并使我的应用程序崩溃,将空值分配为整数。
xB1.addTextChangedListener(new TextWatcher(){
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
if(String.valueOf(charSequence)==null){
numberOfYearsBirthday=0;
}else{numberOfYearsBirthday= Integer.valueOf(charSequence.toString());
}
我也试过下面的代码
charSequence.toString()==""
另外还有下面的
charSequence ==""
但程序忽略了我的 if 语句。我在这里做错了什么?
使用TextUtils.isEmpty(charSequence)
.
第一个解决方案的错误仅检查 null
,这与空字符串不同。
第二个不起作用,因为在 Java 中检查字符串值相等性的正确方法是 stringValue.equals("")
。 ==
将检查两个字符串是否是字符串的同一实例,而事实并非如此。
如果 charSequence
为空,则使用 String::valueOf
will return the text "null" which is different to a null
reference and hence your condition won't work. Also doing charSequence.toString()==""
won't work because this is not the proper way to compare Strings in Java。
试试这个:
// check if charSequence is null or empty ""
if (charSequence == null || charSequence.toString().isEmpty()) {
numberOfYearsBirthday = 0;
} else {
numberOfYearsBirthday = Integer.valueOf(charSequence.toString());
}
在我的应用程序中,我使用的是 EditText。当编辑文本中没有文本时,我想分配 numberOfYearsBirthday=0。
下面的代码我已经试过并调试过了。我已经看到,即使我的 charSequence="" 但它会忽略该语句并移动到 else 语句,从而导致错误并使我的应用程序崩溃,将空值分配为整数。
xB1.addTextChangedListener(new TextWatcher(){
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
if(String.valueOf(charSequence)==null){
numberOfYearsBirthday=0;
}else{numberOfYearsBirthday= Integer.valueOf(charSequence.toString());
}
我也试过下面的代码
charSequence.toString()==""
另外还有下面的
charSequence ==""
但程序忽略了我的 if 语句。我在这里做错了什么?
使用TextUtils.isEmpty(charSequence)
.
第一个解决方案的错误仅检查 null
,这与空字符串不同。
第二个不起作用,因为在 Java 中检查字符串值相等性的正确方法是 stringValue.equals("")
。 ==
将检查两个字符串是否是字符串的同一实例,而事实并非如此。
如果 charSequence
为空,则使用 String::valueOf
will return the text "null" which is different to a null
reference and hence your condition won't work. Also doing charSequence.toString()==""
won't work because this is not the proper way to compare Strings in Java。
试试这个:
// check if charSequence is null or empty ""
if (charSequence == null || charSequence.toString().isEmpty()) {
numberOfYearsBirthday = 0;
} else {
numberOfYearsBirthday = Integer.valueOf(charSequence.toString());
}