当我有连接时,我的XML parser
效果很好,如果丢失,我的活动就会崩溃我希望有一个警告对话框弹出说连接丢失而不是活动崩溃,但我不知道如何做这个。
任何见解都会有所帮助
public class XMLParser {
// constructor
public XMLParser() {
}
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
答案 0 :(得分:1)
上述方法可能无法始终有效。这个是万无一失的
private boolean isOnline() {
try {
myurl = new URL("http://m.google.com");
} catch (MalformedURLException e2) {
e2.printStackTrace();
}
try {
connection = myurl.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setConnectTimeout(3000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = -1;
try {
responseCode = httpConnection.getResponseCode();
} catch (Exception e1) {
e1.printStackTrace();
}
if (!(responseCode == HttpURLConnection.HTTP_OK))
{
return false;
}
return true;