我正在應用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