我正在应用XML解析器来使用此URL上的XML文件:http://www.emmebistudio.com/markers.xml以将地图的标记数据保存到android应用程序中。这是我的代码,应该解析它,但用Eclipse调试器,我已经看到它在第二行返回connected = false,所以,我错在哪里?为什么我的XML解析器不能打开连接?
try{
URL url = new URL("http://www.emmebistudio.com/markers.xml");
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
//Document doc = builder.parse(conn.getInputStream());
NodeList markers = doc.getElementsByTagName("marker");
for (int i = 0; i < markers.getLength(); i++) {
Element item = (Element) markers.item(i);
String name = item.getAttribute("name");
String address = item.getAttribute("address");
String stringLat = item.getAttribute("lat");
String stringLong = item.getAttribute("long");
String icon = item.getAttribute("icon"); //assigned variable for the XML icon attribute
Double lat = Double.valueOf(stringLat);
Double lon = Double.valueOf(stringLong);
map = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
map.addMarker(new MarkerOptions()
.position(new LatLng(lat, lon))
.title(name)
.snippet(address));
}
}catch (Exception e){
// If I can't connect to the file I only see the map with my position
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
e.printStackTrace();
}
你运行在UI线程片断? – Blackbelt 2014-09-22 15:44:03
是的,它只是一个尝试..如果它会顺利运行我会做一个java类 – 2014-09-22 15:47:00
这实际上是问题所在。可能你得到了NetworOnMainThreadException,但是由于你没有打印堆栈跟踪,所以很难说 – Blackbelt 2014-09-22 15:48:45