2011-08-02 77 views
0

我试图获取xml数据并使用异步任务解析它。以下是我所做的: 在OnCreate方法中,我将url作为字符串获取。我测试了我的url,它不返回null。也有权连接到互联网。当试图从URL获取Xml数据时,它返回null

  startDownload start = new startDownload(); 
      start.execute(url.toString()); 

我的异步类:

protected class startDownload extends AsyncTask<String, Void, String>{ 
    @Override 
    protected void onPreExecute() { 

     eczaDialog = ProgressDialog.show(ListViewXML.this,"", "Loading..."); 
    } 
    @Override 
    protected String doInBackground(String... aurl) { 
     try { 
      URL url = new URL(aurl[0]); 

      DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance(); 
      DocumentBuilder db = dbf.newDocumentBuilder(); 
      Document doc = db.parse(new InputSource(url.openStream())); 
      doc.getDocumentElement().normalize(); .... 

当调试我的代码,我看到这个doc变量返回null。我不明白问题在哪里。我希望你能帮我找出谢谢。

回答

1

您必须获取xml的内容。您可以使用此代码返回字符串中的内容,然后您可以创建一个XML对象:

public static String getStringPage(String url){ 
    StringBuffer stringBuffer = new StringBuffer(); 
    BufferedReader bufferedReader = null; 
    HttpClient httpClient = null; 
    HttpGet httpGet = null; 
    URI uri = null; 
    HttpResponse httpResponse = null; 
    InputStream inputStream = null; 
    String HTMLCode = null; 


    //Create client and a query to get the page 
     httpClient = new DefaultHttpClient(); 
     httpGet = new HttpGet(); 

     //Set the query with the url in parameter 
     try { 
      uri = new URI(url); 
     } catch (URISyntaxException e) { 
      e.printStackTrace(); 
     } 
     httpGet.setURI(uri); 

     //Execute the query 
     try { 
      httpResponse = httpClient.execute(httpGet); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     //Create a buffer to get the page 
     try { 
      inputStream = httpResponse.getEntity().getContent(); 
     } catch (IllegalStateException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 

     //Get the buffer caracters 
    try { 
     HTMLCode = bufferedReader.readLine(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    while (HTMLCode!= null){ 
     stringBuffer.append(HTMLCode); 
     stringBuffer.append("\n"); 
     try { 
      HTMLCode = bufferedReader.readLine(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    //Return the string of the page code 
    return stringBuffer.toString(); 
} 
+0

了解并完成它需要时间因为我是Android的noob。非常感谢您的帮助 :) – ophe

相关问题