2012-06-17 46 views
3

我的XML parser当我有连接时很好用,如果丢失我的活动会崩溃我想要一个警告对话框弹出窗口说连接丢失而不是活动崩溃但我不知道如何去做这个。XML分析器无连接错误

任何有识之士将有助于

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)); 
     } 
} 

回答

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;