I use google places api to return a list of interesting places nearby. Each place and its attributes are enclosed in result and /result tag. After encountering the first /result tag I get Network on main thread exception whenever there is parser.next() statement.
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();
}
Each object of Locations class represent a place. I have used a separate thread to perform httpurl connection activities and have also set read timeout to 3 mins. (below class is used to open http network connection)
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;
}
}