0

I'm trying to read an xml file from the internet.

This is the code i'm using:

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

and I'm getting this ex:

android.os.NetworkOnMainThreadException

I'm trying to do this with an async method following the answers. This is the code I tried:

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

}

But the document is null.

Stewbob
  • 16,759
  • 9
  • 63
  • 107
Edgar
  • 467
  • 1
  • 8
  • 23

1 Answers1

0

Try to include the Web Call logic inside the AsyncTask.

FYI, you can do background process inside the doInBackground() method of AsyncTask.

Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295