Question

I'm getting a list of venues from foursquare and I need the name, the address and the city of each venue that I get. Here my problem is if address or city is empty, it gives an error and says " JSON Exception: No value for address". I tried different ways to fix it but couldn't solve the problem. I hope you can help me. Thank you.

JSONObject b = venues.getJSONObject(i);
JSONObject location = b.getJSONObject("location");

String name = "";
String address = "";
String city = "";

if ("".equals(b.get("name"))) {
    //  Toast.makeText(Activity2.this,"Name of Place: " +name+ " Location: "+country, Toast.LENGTH_SHORT).show();
    name = "No place ";
} else {
    name = b.getString("name");
}

if ("".equals(location.getString("address"))) {
    address = "No address";
} else {
    address = location.getString("address");
}

if ("".equals(location.getString("city"))) {
    city = "No city";
} else {
    city = location.getString("city");
}

name = "Name of the place: " + name; 
// + " Address: "+ address + "  City: " + city;
list.add(name);
Was it helpful?

Solution

You likely need to call the has() method prior to calling getString to avoid the exception. But there's an even simpler way - just use the optString instead of getString, which will return the "fallback" string if the value does not exist.

String name = location.optString("name", "No Place");
String address = location.optString("address", "No Address");
String city = location.optString("city", "No City");

OTHER TIPS

The .Json object "location" doesn´t contain address value, you have to add another evaluation.

location.getString("address") = null;

for example:

if ((location.getString("address") = null) || "".equals(location.getString("address"))) {
    address = "No address";
} else {
    address = location.getString("address");
}

or see selbie´s solution using optString() method

String address = location.optString("address", ""); //where "" is a default value.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top