Android HttpClient : NetworkOnMainThreadException

user1531240 picture user1531240 · Jul 31, 2012 · Viewed 8.4k times · Source

I have some code below:

protected void testConnection(String url) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    ResponseHandler<String> responsehandler = new BasicResponseHandler();

    try {
        String connection = httpclient.execute(httpget, responsehandler);
        Toast.makeText(getBaseContext(), R.string.connection_succeed, Toast.LENGTH_SHORT).show();
        view_result.setText(connection);
    } catch(IOException e) {
        Toast.makeText(getBaseContext(), R.string.connection_failed, Toast.LENGTH_SHORT).show();
    }
    httpclient.getConnectionManager().shutdown();
}

and add a permission in Menifest:

<uses-permission android:name="android.permission.INTERNET"/>

But it goes an exception: NetworkOnMainThreadException, How can i do?

Answer

nkr picture nkr · Jul 31, 2012

On ICS and later you cannot do network operations on the UI thread anymore. Instead you are forced to create a new thread and do your networking stuff there.

Possible tools are Android's AsyncTask and the normal Java Thread.

A good tutorial can be found here: Android Threads, Handlers and AsyncTask - Tutorial