Reputation: 95
I am trying to get the latitude and longitude of a place with the following code:
public LatLng findAddress(String place) {
try {
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?address="
+ place + "&sensor=false";
URL url = new URL(googleMapUrl);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
String a = "";
StringBuilder sb = jsonResults;
JSONObject jsonObj = new JSONObject(sb.toString());
JSONArray resultJsonArray = jsonObj.getJSONArray("results");
JSONObject before_geometry_jsonObj = resultJsonArray
.getJSONObject(0);
JSONObject geometry_jsonObj = before_geometry_jsonObj
.getJSONObject("geometry");
JSONObject location_jsonObj = geometry_jsonObj
.getJSONObject("location");
String lat_helper = location_jsonObj.getString("lat");
double lat = Double.valueOf(lat_helper);
String lng_helper = location_jsonObj.getString("lng");
double lng = Double.valueOf(lng_helper);
return new LatLng(lat, lng);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new LatLng(0,0);
}
}
But when I run it, it goes to the catch-part (right after the
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
part.) Even after some time revising the code, I do not seem to have found the reason behind this phenomenon. (the reason why I do not use the GeoCoder service is because it is not stable, and requires a reboot on every device I have tested on)
Upvotes: 0
Views: 42
Reputation: 95
In the meanwhile I have solved it. I got android.os.NetworkOnMainThreadException, I should not have run a network call on the Main thread. Thank you all for your help.
Upvotes: 1