5

I have a problem that I want to parse an XML-file on the web. Now mine HttpResponce gets too much time too read that XML-file, so I get the error "Become Runtime Error" for my GUIs.

try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://chukk.nuzoka.com/name.xml");

        HttpResponse httpResponse = httpClient.execute(httpPost);

        HttpEntity httpEntity = httpResponse.getEntity();
        line = EntityUtils.toString(httpEntity);


    } catch (UnsupportedEncodingException e) {
        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    } catch (MalformedURLException e) {
        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    } catch (IOException e) {
        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    }

Any help is appreciated :)

4
  • your doing this in a seperate thread right? Commented Feb 26, 2012 at 21:46
  • Just a side note, consider using StreamReader instead of EntityUtils.toString, for memory usage improvement.
    – yorkw
    Commented Feb 26, 2012 at 22:43
  • @yorkw Have you got anything to back that up? I'm using EntityUtils..
    – nhaarman
    Commented Feb 26, 2012 at 23:12
  • @Niek, check out this SO question.
    – yorkw
    Commented Feb 27, 2012 at 0:06

3 Answers 3

3

As a general rule in UI programming, not only Android, you should move to a background thread any heavy-processing/time consuming task.

There are good facilities for that which helps you performing the long task in background and post its final/intermediate results to the UI thread in Android, such as AsyncTask and Handlers.

1

In addition to what Binyamin Sharet said, there is a special mode you can use during development that can catch design errors like this.

StrictMode is most commonly used to catch accidental disk or network access on the application's main thread, where UI operations are received and animations take place. Keeping disk and network operations off the main thread makes for much smoother, more responsive applications. By keeping your application's main thread responsive, you also prevent ANR dialogs from being shown to users.

1

You want to use an HTTP GET request instead of a POST since you aren't posting any parameters to the web server.

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://chukk.nuzoka.com/name.xml"));
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.