Pootie Tang Pootie Tang - 6 months ago 17
JSON Question

Checking for null values in Java

I'm trying to modify an Android app that is pulling some JSON from a server..

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


Then using that to construct an object from my Sponsor class..

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. 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:

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.

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.

Answer

"getAddress2()" isn't returning the literal string "null". It's returning a null reference and the StringBuilder is converting it to a "null" String when you print it in the concatenation. 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:

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

Now you'll never return a null reference and you can safely use it without any checks.

Comments