2012-04-23 11 views
0

私はインターネットからxmlファイルを読み込もうとしています。XMLをHTTP Androidから読む

これは私が使用しているコードです:

HttpClient client = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://www.mypage.com/version.xml"); 
HttpResponse resp = client.execute(httppost); 

と私は、このEXを取得していた:

android.os.NetworkOnMainThreadException

を私がしようとしています答えに続く非同期メソッドでこれを行います。 これは私が試したコードです:

public class Download extends AsyncTask<String, Void, Document> { 

@SuppressWarnings("unused") 
private Exception exception; 
public Document document; 

public Download(String url) 
{ 
    this.execute(url); 
} 

@Override 
protected Document doInBackground(String... url) { 
    try { 
     HttpUriRequest request = new HttpGet(url.toString()); 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpResponse response = httpClient.execute(request); 

     StatusLine statusLine = response.getStatusLine(); 
     int statusCode = statusLine.getStatusCode(); 
     if (statusCode == 200) { 
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder builder = factory.newDocumentBuilder(); 
      document = builder.parse(response.getEntity().getContent()); 
      return document; 
     } else { 
      throw new IOException("Download failed, HTTP response code " 
        + statusCode + " - " + statusLine.getReasonPhrase()); 
     }    

    } catch (Exception e) { 
     exception = e; 
     return null; 
    } 
} 

protected void onPostExecute(Document doc) 
{ 
    // TODO: check this.exception 
    // TODO: do something with the feed 
    document = doc; 
} 

} 

しかし、文書はnullです。

+0

例外はありますか?バックグラウンドスレッドを使用します。 – SLaks

+1

メインスレッドでのネットワーク操作を避けるほうがよいです。 – kosa

+0

このスレッドをチェック: http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – Plutoz

答えて

0

AsyncTaskの内部にWeb呼び出しロジックを含めるようにしてください。

FYIでは、AsyncTaskのdoInBackground()メソッド内でバックグラウンドプロセスを実行できます。

+0

または方向変更の問題を取り除くには、 'AsyncTaskLoader'を実行してください。 –

+0

私は試しています、私は質問を編集しました、 チェックアウトしてください – Edgar