简体   繁体   English

在Java中检查空值

[英]Checking for null values in Java

I'm trying to modify an Android app that is pulling some JSON from a server.. 我正在尝试修改从服务器提取一些JSON的Android应用。

JSONObject mResult = new JSONObject((String) result);

Then using that to construct an object from my Sponsor class.. 然后使用它来构造我的Sponsor类的对象。

Gson mGson = new Gson();
mSponsor = mGson.fromJson(mResult.getJSONObject("data").getJSONObject("sponsor").toString(), Sponsor.class);

Sponsor class is just a shell with setters and getters, no logic done. 赞助者类只是一个带有setter和getter的shell,没有逻辑。 Something like this: 像这样:

public class Sponsor {

    @SerializedName("address1")
    private String Address1;
    @SerializedName("address2")
    private String Address2;

    public Sponsor(String address1, String address2) {
        Address1 = address1;
        Address2 = address2;
    }

    public Sponsor() {
        Address1 = "";
        Address2 = "";
    }

    public String getAddress1() {
        return Address1;
    }

    public void setAddress1(String address1) {
        Address1 = address1;
    }

    public String getAddress2() {
        return Address2;
    }

    public void setAddress2(String address2) {
        Address2 = address2;
    }
}

The app puts the address in a TextView like so: 该应用程序将地址放入TextView中,如下所示:

txtAddress = (TextView) view.findViewById(R.id.txt_sponsor_address);
txtAddress.setText(mSponsor.getAddress1() + "\n" + mSponsor.getAddress2());

This all works, except when the server returns null for address2 , in which case the literal text "null" is printed in the TextView where address2 should be. 这一切都有效,除非服务器为address2返回null ,在这种情况下,文本文本“ null”被打印在TextView中应该位于address2的位置。

My question is how can i get rid of the "null"? 我的问题是如何摆脱“空值”?

I've tried a few different things, started with a simple ternary statement and got more and more verbose and nothing has worked so for. 我尝试了一些不同的事情,从简单的三元语句开始,到越来越冗长,没有任何效果。

Here is the latest and most ridiculous-looking thing I've tried so far: 这是到目前为止我尝试过的最新,最荒谬的方法:

String addr2 = ((String) mSponsor.getAddress2()).trim();
String a2;
if((addr2 == "null") || (addr2 == "")) a2 = (String) "";
else a2 = (String) addr2;

txtAddress.setText(mSponsor.getAddress1() + "\n" + a2);

This causes the app to crash when I open that Activity. 当我打开该活动时,这将导致应用程序崩溃。

I'm a noob at Java so please provide references if you can. 我是Java的菜鸟,所以请提供参考。

You could create another getter in your Sponsor class, where you'd put your logic to get a formatted address : 您可以在Sponsor人类中创建另一个getter,在其中您可以输入逻辑来获取格式化的地址:

public String getFormattedAddress() {
    if (!TextUtils.isEmpty(Address1) && !TextUtils.isEmpty(Address2)
        && !Address1.equalsIgnoreCase("null") && !Address2.equalsIgnoreCase("null")) {
      return (Address1 + "\n" + Address2);
    }
    if (!TextUtils.isEmpty(Address1) && !Address1.equalsIgnoreCase("null")) {
      return (Address1);
    }
    if (!TextUtils.isEmpty(Address2) && !Address2.equalsIgnoreCase("null")) {
      return (Address2);
    }
    return ("");
}

And then simply setText with : 然后简单地使用setText:

txtAddress.setText(mSponsor.getFormattedAddress());

"getAddress2()" isn't returning the literal string "null". “ getAddress2()”未返回文字字符串“ null”。 It's returning a null reference and the StringBuilder is converting it to a "null" String when you print it in the concatenation. 它返回null引用,并且在串联中打印时,StringBuilder会将其转换为“空”字符串。 That's why it crashes when you try to trim the word. 这就是为什么当您尝试修剪单词时它崩溃的原因。

A simple way to fix it is to put the ternary operator in the getter itself like so: 解决该问题的一种简单方法是将三元运算符放入getter本身,如下所示:

public String getAddress2() {
  return (Address2 == null) ? "" : Address2;
}

Now you'll never return a null reference and you can safely use it without any checks. 现在,您将永远不会返回空引用,并且无需进行任何检查就可以安全地使用它。

You should not use : 您不应该使用:

if((addr2 == "null")

For string comparaison use: 对于字符串比较,请使用:

if (addr2.equalsIgnoreCase("null"))
String addr2 = mSponsor.getAddress2();
if(!TextUtils.isEmpty(addr2) || !addr2.equalsIgnoreCase("null")
     txtAddress.setText(mSponsor.getAddress1() + "\n" + addr2);
else
     txtAddress.setText(mSponsor.getAddress1());

How about this? 这个怎么样?

// if null, addr2="", if not null, addr = getAddress2()'s result 
String addr2 = mSponsor.getAddress2() == null ? "" : ((String) mSponsor.getAddress2()).trim();

txtAddress.setText(mSponsor.getAddress1() + "\n" + addr2);

Try this for your getter code: 试试这个你getter的代码:

 public String getAddress2() {
    if (Address2.equals("null")) {
        Address2="";
    }
    return Address2;
 }

Of course, you can do the same with your other getter for Address1 . 当然,您可以对Address1的其他getter进行相同的操作。 Also, if you want to check for an empty string, use Address2.length() == 0 as opposed to Address2 == "" . 另外,如果要检查空字符串,请使用Address2.length() == 0而不是Address2 == ""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM