2013-02-28 90 views
0

我在應用程序打開之前遇到了一些與我的XMLParser有關的問題。我得到的錯誤是:當我嘗試解析XML時出錯

錯誤:org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)

這裏是我的XMLParser的代碼:

public class XMLParser { 

    public XMLParser(){ 
    } 

    public String getXmlFromUrl(String url){ 
     String xml = null; 

     try{ 
      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; 
    } 

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

} 

而在我的主要活動我把它像thath:

XMLParser parser = new XMLParser(); 
String xml = parser.getXmlFromUrl(URL); 
Document doc = parser.getDomElement(xml); 

所以如果你c幫助我什麼可能導致這個問題。

+0

後。疊加。跟蹤。 – njzk2 2013-02-28 10:35:47

+0

請發佈整個堆棧跟蹤 – Abubakkar 2013-02-28 10:36:09

+0

這裏:http://pastebin.com/pfkzL9hP – HyperX 2013-02-28 10:39:20

回答

2

堆棧跟蹤告訴的你到底什麼錯:你不應該在UI線程上做網絡的東西。

良好的解決辦法:不要在UI線程上做網絡的東西,用的AsyncTask或他人。

快速修復:你的網絡的東西之前,補充一點:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
StrictMode.setThreadPolicy(policy); 

http://www.techblogistech.com/2011/11/how-to-fix-the-android-networkonmainthreadexception/

0

你得到一個android.os.NetworkOnMainThreadException?您無法在主要活動線程上調用網絡API(即httpClient.execute())。相反,您需要在AsyncTask中運行它。如果您需要關於如何完成此操作的幫助,請點擊here