2

Earlier I asked to get the address of specific coordinates. Now I want to parse the JSON structure which can be received with URL https://maps.google.com/maps/api/geocode /json?latlng=48.906233407932675,2.433183006942272 I used the following code, but this causes a crash of my application.

public void parseJSONLocation(LatLng point)
{
    Toast.makeText(getApplicationContext(), "Test", Toast.LENGTH_LONG).show();
    double lat = point.latitude;
    double lng = point.longitude;

    JSONObject ret = getJSONLocationInfo(lat, lng);
    JSONObject location;
    String location_string = "";

    try {

        //Get JSON Array called "results" and then get the 0th complete object as JSON        
        location = ret.getJSONArray("results").getJSONObject(0); 
        // Get the value of the attribute whose name is "formatted_string"
        location_string = location.getString("formatted_address");
        //Toast.makeText(getApplicationContext(), "formattted address:" + location_string, Toast.LENGTH_LONG).show();
    } catch (JSONException e1) {
        e1.printStackTrace();

    }
}

public JSONObject getJSONLocationInfo(double lat, double lng)
{
    HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&key=AIzaSyB3hYTOGwj2FM9rSCYxTag1VkJXpFRmkOc");
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
        } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonObject;
}

Does anyone has an idea to solve this?

NiAu
  • 535
  • 1
  • 12
  • 32
  • 07-13 15:35:14.410: E/AndroidRuntime(5772): FATAL EXCEPTION: main 07-13 15:35:14.410: E/AndroidRuntime(5772): android.os.NetworkOnMainThreadException 07-13 15:35:14.410: E/AndroidRuntime(5772): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) 07-13 15:35:14.410: E/AndroidRuntime(5772): at java.net.InetAddress.lookupHostByName(InetAddress.java:391) – NiAu Jul 13 '14 at 13:42
  • `NetworkOnMainThreadException` you cannnot perform network operations on main thread, move your away from ui thread, use `AsyncTask` or library like: http://loopj.com/android-async-http/ or https://github.com/square/retrofit etc – Than Jul 13 '14 at 13:52
  • http://stackoverflow.com/questions/24678522/http-post-request-with-android-crashes/24678745#24678745 – Than Jul 13 '14 at 13:53

0 Answers0