【问题标题】:how to check if a variable is null or not? [closed]如何检查变量是否为空? [关闭]
【发布时间】:2012-04-19 07:23:31
【问题描述】:

您好,我需要检查两个变量的值是否为空。如果它们不为空,我必须使文本视图可见。同样,我编写了以下代码

 if (offer.Price() != null ) {
        if(offer.getName() !=null)
        {
        Price.setVisibility(View.VISIBLE);
        Price.setText(offer.getName()+" Price: $"+offer.getPrice());
    }
    }

但它不起作用。即即使变量值为 null 并且 textview 中的文本显示为“null Price: $null”,textview 也是可见的。首先我尝试使用以下代码。但这也是不工作

    if (offer.getPrice() != null && offer.getName() !=null) {
        Price.setVisibility(View.VISIBLE);
        Price.setText(offer.getName()+" Price: $"+offer.getPrice());
    }

请帮我解决它....

【问题讨论】:

标签: android null textview


【解决方案1】:

试试看:

if (offer.getPrice() != null && offer.getName() !=null) {
        Price.setVisibility(View.VISIBLE);
        Price.setText(offer.getName()+" Price: $"+offer.getPrice());
    }else{
 Price.setVisibility(View.GONE);
}

或者那个

if (offer.getPrice() != null && offer.getName() !=null
&& !offer.getPrice().equals("null") && !offer.getName().equals("null")) {
        Price.setVisibility(View.VISIBLE);
        Price.setText(offer.getName()+" Price: $"+offer.getPrice());
    }else{
 Price.setVisibility(View.GONE);
}

【讨论】:

  • !offer.getPrice().equals("null") 有一些魔力... :)
  • @seethalakshmi,是的,尝试在空对象引用上调用虚拟方法“boolean java.lang.String.equals(java.lang.Object)”
【解决方案2】:
 if (offer.getPrice() != null && !"".equalsIgnoreCase(offer.getPrice())
    && offer.getName() !=null && !"".equalsIgnoreCase(offer.getName())) {
    Price.setVisibility(View.VISIBLE);
    Price.setText(offer.getName()+" Price: $"+offer.getPrice());
}

【讨论】:

  • 为什么不简单地使用 TextUtils.isEmpty 而不是那些冗长的检查?
  • 确实.. :D public static boolean isEmpty(CharSequence str) { if (str == null || str.length() == 0) return true;否则返回假;所以猜猜这​​更有意义.. 谢谢 Waqas
  • 我已经尝试过 TextUtils.isEmpty 但这也不起作用
  • 请检查 offer.getPrice().trim();和 offer.getName().trim();可能是您将空间作为价值观,这就是您遇到问题的原因。
  • 我认为您正在调用 Web 服务,因此您可能将“Price:”的值设为“null”。注意:这里的 null 表示文本不为 null(空)。
猜你喜欢
  • 2013-09-05
  • 1970-01-01
  • 2017-11-05
  • 2011-05-20
  • 2012-02-05
  • 2019-04-19
相关资源
最近更新 更多