Nirav Ranpara
Nirav Ranpara

Reputation: 13785

JSON format Error

I want to pass address and want lat and long . But I got complete String from maps.google.com. But there is error in JSON format.

I try below Code

Error :Couldn't get connection factory client

getLocationInfo("3 cité Nollez Paris France");

public static void getLocationInfo(String address) {
        StringBuilder stringBuilder = new StringBuilder();
        try {

        address = address.replaceAll(" ","%20");    

        HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();


            response = client.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }

            System.out.print(stringBuilder);
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }

        JSONObject jsonObject = new JSONObject();
        try {

            jsonObject = new JSONObject(stringBuilder.toString());

            longitute = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lng");

                System.out.print(longitute);


                latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lat");

                System.out.print(latitude);

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

      //  return jsonObject;
    }

LOGCAT

{
   "results" : [
      {
         "address_components" : [
            {
                "long_name" : "3",
                "short_name" : "3",
                "types" : [ "street_number" ]
             },
             {
                "long_name" : "Cité Nollez",
                "short_name" : "Cité Nollez",
                "types" : [ "route" ]
             },
             {
                "long_name" : "18th arrondissement of Paris",
                "short_name" : "18th arrondissement of Paris",
                "types" : [ "sublocality", "political" ]
             },
             {
                "long_name" : "Paris",
                "short_name" : "Paris",
               "types" : [ "locality", "political" ]
             },
             {
              "long_name" : "Paris",
                "short_name" : "75",
                "types" : [ "administrative_area_level_2", "political" ]
             },
             {
                "long_name" : "Ã?le-de-France",
                "short_name" : "IdF",
                "types" : [ "administrative_area_level_1", "political" ]
             },
             {
                "long_name" : "France",
                "short_name" : "FR",
               "types" : [ "country", "political" ]
            },
             {
             "long_name" : "75018",
              "short_name" : "75018",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "3 Cité Nollez, 75018 Paris, France",
         "geometry" : {
            "location" : {
               "lat" : 48.89376110,
               "lng" : 2.33742180
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 48.89511008029150,
                  "lng" : 2.338770780291502
               },
               "southwest" : {
                  "lat" : 48.89241211970850,
                  "lng" : 2.336072819708498
               }
            }
         },
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}
03-14 13:51:35.776: I/MapActivity(1430): Handling network change notification:CONNECTED
03-14 13:51:35.776: E/MapActivity(1430): Couldn't get connection factory client

Upvotes: 2

Views: 994

Answers (3)

Harish
Harish

Reputation: 3117

Add the following code in your Map activity before super.onCreate()

ExampleActivity:-

 public class ExampleActivity extends Activity {

    // url to make request
    private static String url = "http://maps.googleapis.com/maps/api/geocode/json?address="+address.replace(" ", "%20")+"&sensor=true";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tvlat = (TextView) findViewById(R.id.tvlat);
        tvlng = (TextView) findViewById(R.id.tvlng);

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
             System.out.println("Location Latitude"
                + json.getJSONArray("results").getJSONObject(0)
                        .getJSONObject("geometry")
                        .getJSONObject("location").getString("lat"));

               System.out.println("Location Longitude"
                + json.getJSONArray("results").getJSONObject(0)
                        .getJSONObject("geometry")
                        .getJSONObject("location").getString("lng"));    
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

JSONPareser:-

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();            

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

Then run your app, it worked fine for me.

Upvotes: 2

Jai Kumar
Jai Kumar

Reputation: 920

There is no need to worry if that "couldn't get connection error" while using maps.. it will work fine even after the occurrence of that.. If your code doesnt work then there is other reason. check to it..

Upvotes: 0

Yasir Malik
Yasir Malik

Reputation: 439

Have you enabled these permissions.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>

Upvotes: 0

Related Questions