Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpResponse in Android

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 :)

like image 417
Emraan Khalil Avatar asked Feb 26 '12 21:02

Emraan Khalil


2 Answers

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.

like image 66
MByD Avatar answered Oct 13 '22 09:10

MByD


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.

like image 29
Dmitry Avatar answered Oct 13 '22 09:10

Dmitry