2013-02-28 165 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