首页 > 解决方案 > 检查类中的字符串是否为空

问题描述

我知道我的问题与之前的某个问题重复,我尝试了我从中看到的所有解决方案,但没有解决方案对我有用

我有一个名为 FilingModel 的类和一个名为 getReason 的方法,我的 tvReason TextView 总是得到一个空值

public class FilingAdapter extends RecyclerView.Adapter<FilingAdapter.FilingHolder> {
  List<FilingModel> lists;
    @Override
    public void onBindViewHolder(@NonNull FilingHolder holder, int position) {
     FilingModel model = lists.get(position);
     holder.tvReason.setText(model.getReason());
   }

}
public class FilingModel {

    private String reason;

    public FilingModel(String reason) {
        this.reason = reason;
    }

    public String getReason() {
        if ( reason.isEmpty() || TextUtils.isEmpty(reason) || reason.equals(null)) {
           reason = "-";
        }
        return reason;
    }
}


标签: javaandroid

解决方案


String checks for null are rather straight forward (once you have done it):

First you want to check if the instance is null (otherwise all further manipulation might fail):

 if(reason == null)

Then you want to check if it is empty as you already did it but maybe you want to trim it first (to remove all whitespaces):

if(reason == null || reason.trim().isEmpty())

as you can see you can chain the conditions with or since Java will stop evaluating the conditions once one of them was found true . So if your string is null, Java will not evaluate if it is empty.

And that's all you need, null and isEmpty (and optionally with a trim())

public String getReason() {
    if(reason==null || reason.trim().isEmpty()){
       reason = "-";
    }
    return reason;
}

推荐阅读