3

using this method for getting Latitude and longitute of location entered by user working good in java but when I use this method in android , app stops automatically and exceptions/errors appears are shown in attached image

public static String[] getLatLongPositions(String address) throws Exception
{
    int responseCode = 0;
    String api = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + URLEncoder.encode(address, "UTF-8") + "&sensor=true";
    URL url = new URL(api);
    HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();
    httpConnection.connect();
    responseCode = httpConnection.getResponseCode();

    if(responseCode == 200)
    {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();;
        Document document = builder.parse(httpConnection.getInputStream());
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("/GeocodeResponse/status");
        String status = (String)expr.evaluate(document, XPathConstants.STRING);
        if(status.equals("OK"))
        {
            expr = xpath.compile("//geometry/location/lat");
            String latitude = (String)expr.evaluate(document, XPathConstants.STRING);
            expr = xpath.compile("//geometry/location/lng");
            String longitude = (String)expr.evaluate(document, XPathConstants.STRING);
            return new String[] {latitude, longitude};
        }
        else
        {
            throw new Exception("Error from the API - response status: "+status);
        }
    }
    return null;
}

Error:

error

lorond
  • 3,856
  • 2
  • 37
  • 52
imabdullah
  • 327
  • 1
  • 5
  • 24
  • You're getting network on main thread exception. Fix it – Shaishav Aug 07 '16 at 05:05
  • how ? I have no idea about this exception . Actually I'm beginner , working correctly in java but not in android . Thanks @shaishav – imabdullah Aug 07 '16 at 05:12
  • Ok..n/w operations are not allowed on the main/UI thread. You have to spawn a new thread (or an `Asynctask` or something) and do the n/w call there. You can get examples if you search for that exception. – Shaishav Aug 07 '16 at 05:13
  • Inserting Stacktraces as image is bad style. The next time please copy the text to clipboard and paste it as text into your question. – Robert Aug 07 '16 at 12:47

0 Answers0