我使用 google places api 返回附近有趣地点的列表。每个地点及其属性都包含在 result 和 /result 标记中。遇到第一个 /result 标记后,只要有 parser.next() 语句,我就会在主线程异常上得到网络。
try {
int type = parser.getEventType();
Locations obj = null;
while (type != XmlPullParser.END_DOCUMENT) {
String name = parser.getName();
switch (type) {
case XmlPullParser.START_TAG: {
if (name.equalsIgnoreCase("result"))
{obj = new Locations();}
else if (name.equalsIgnoreCase("name"))
obj.name = parser.nextText();
else if (name.equalsIgnoreCase("vicinity"))
obj.address = parser.nextText();
else if (name.equalsIgnoreCase("lat"))
lat = parser.nextText();
else if (name.equalsIgnoreCase("lng")) {
lng = parser.nextText();
LatLng latLng = new LatLng(Double.parseDouble(lat),Double.parseDouble(lng));
obj.latlng = latLng;
}
break;
}
case XmlPullParser.END_TAG: {
if (name.equalsIgnoreCase("result")) {
entries.add(obj);
}
break;
}
}//End Switch Case
type = parser.next();
}//End While Block
} //End try block
catch (IOException ioex)
{
ioex.printStackTrace();
}
catch (XmlPullParserException ioex)
{
ioex.printStackTrace();
}
catch (Exception ioex)
{
ioex.printStackTrace();
}
Locations 类的每个对象都代表一个地点。我使用了一个单独的线程来执行 httpurl 连接活动,并且还将读取超时设置为 3 分钟。(下面的类是用来打开http网络连接的)
public class DownloadxmlTask {
public String status=null;
public InputStream isi=null;
private InputStream loadXmlfromnetwork(String url) {
InputStream in = null;
try {
URL urlobj = new URL(url);
HttpURLConnection conobj = (HttpURLConnection) urlobj.openConnection();
conobj.setReadTimeout(3*60000);
in = conobj.getInputStream();
isi=in;
status = in.toString();
wait(3*60000);
conobj.disconnect();
} catch (Exception ex) {
status =ex.getLocalizedMessage().toString();
}
return in;
}
protected InputStream doInBackground(String params) {
final String url = params;
Thread newthread=new Thread() {
@Override
public void run() {
loadXmlfromnetwork(url);
}
};
newthread.start();
return isi;
}
}