java - 检查类中的字符串是否为空
问题描述
我知道我的问题与之前的某个问题重复,我尝试了我从中看到的所有解决方案,但没有解决方案对我有用
我有一个名为 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;
}
}
解决方案
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;
}
推荐阅读
- java - 如何在没有android的情况下移动像圆周运动这样的视图?
- laravel - vim : 术语“vim”不被识别为 cmdlet 的名称?
- jquery - 在准备好的文档中显示页面
- python - 在 PostgreSQL 中匹配相似的长字符串并让它告诉我它们有多相似
- swift - 快速的问题,如何在 00:00 停止我的计时器而不是负数
- bash - 加载 Docker 容器后运行 Bash 脚本
- javascript - 如何获取其他页面的完整代码并放入文本区域
- python - 如何在 Pycharm 中向下/向上移动方法?
- android - 数据未从 Android 上传到 Firebase 数据库
- python - python logger.error dosn't ' 当文件丢失时写入错误日志