2011-08-02 73 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

相關問題