Java 在UI线程上使用HttpURLConnection(内部活动)
使用此方法获取用户输入的位置的纬度和经度 在java中运行良好,但当我在android中使用此方法时,应用程序会自动停止,异常/错误显示在所附的图像中Java 在UI线程上使用HttpURLConnection(内部活动),java,android,Java,Android,使用此方法获取用户输入的位置的纬度和经度 在java中运行良好,但当我在android中使用此方法时,应用程序会自动停止,异常/错误显示在所附的图像中 public static String[] getLatLongPositions(String address) throws Exception { int responseCode = 0; String api = "http://maps.googleapis.com/maps/api/geocode/xml?addr
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;
}
错误:
您的网络在主线程上出现异常。怎么解决?我不知道这个例外。实际上,我是初学者,在java中可以正常工作,但在android中不能。谢谢@shaishavOk..n/w操作不允许在主/UI线程上进行。您必须生成一个新线程(或一个
Asynctask
或其他什么)并在那里执行n/w调用。如果搜索该异常,您可以获得示例。将Stacktraces作为图像插入是错误的样式。下次请将文本复制到剪贴板,并将其作为文本粘贴到问题中。