Search code examples
androidandroid-asynctaskhttpclientrunnable

HttpClient queries on main thread keeps crashing when in Runnable


I've expierenced this code runs smoothly on Android 2.2. But on Android 4.0 it crashes.

I am assuming that, It's caused by HttpClient. So I moved the code into a Runnable, but it keeps crashing.

new Runnable() {

        @Override
        public void run() {
            try {        
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI(serverroot + URI_ARGS));
                client.execute(request);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.run();

Is there another way to do this without using AsyncTask?


Solution

  • Starting from API11 there is new exception NetworkOnMainThreadException that will be thrown if you are working with network on UI thread, so you need to move you code out of UI Thread. Runnable is just interface it won't help you without actually Thread.

    new Thread(new Runnable() {
    
        @Override
        public void run() {
            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI(serverroot + URI_ARGS));
                client.execute(request);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();