0

I have the following code from my application:

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.pagesbyz.com");
ResponseHandler<String> resHandler = new BasicResponseHandler();
try {
    String page = httpClient.execute(httpGet, resHandler);
    Toast.makeText(getApplicationContext(), "SUCCESS", 2000).show();
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

I added the following line to my Manifest:

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

My app FC with the following LogCat error:

11-04 11:59:14.137: E/AndroidRuntime(11052): FATAL EXCEPTION: main
11-04 11:59:14.137: E/AndroidRuntime(11052): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.testing/com.test.testing.AndroidFragmentation}: android.os.NetworkOnMainThreadException
11-04 11:59:14.137: E/AndroidRuntime(11052):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2356)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at android.app.ActivityThread.access$600(ActivityThread.java:150)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at android.os.Looper.loop(Looper.java:137)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at android.app.ActivityThread.main(ActivityThread.java:5195)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at java.lang.reflect.Method.invokeNative(Native Method)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at java.lang.reflect.Method.invoke(Method.java:511)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at dalvik.system.NativeStart.main(Native Method)
11-04 11:59:14.137: E/AndroidRuntime(11052): Caused by: android.os.NetworkOnMainThreadException
11-04 11:59:14.137: E/AndroidRuntime(11052):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:653)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at com.test.testing.AndroidFragmentation.onCreate(AndroidFragmentation.java:36)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at android.app.Activity.performCreate(Activity.java:5104)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
11-04 11:59:14.137: E/AndroidRuntime(11052):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2260)

Any idea how to resolve it? Thanks!

Si8
  • 9,141
  • 22
  • 109
  • 221
  • 3
    Search for `android.os.NetworkOnMainThreadException` on google – Alexis C. Nov 04 '13 at 17:04
  • 2
    When reading Android stack traces, always look for a 'Caused by:'. There may be any number. If present, then the actually _useful_ bit of the stack trace will start at the last one. – David Given Nov 04 '13 at 17:10

4 Answers4

3

This is explained here. You should use an AsyncTask for network access, or Thread / HandlerThread. Network access on main (UI) thread is forbidden since API 11.

you could try something like this :

private class HttpTask extends AsyncTask<String, Void, Void>{
    @Override
    protected Void doInBackground(String... params) {
        String url = params[0];
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        ResponseHandler<String> resHandler = new BasicResponseHandler();
        try {
            String page = httpClient.execute(httpGet, resHandler);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        Toast.makeText(getApplicationContext(), "SUCCESS", 2000).show();
    }
}

and from your Activity/Fragment

HttpTask task = new HttpTask();
task.execute(url);
2Dee
  • 8,609
  • 7
  • 42
  • 53
  • Thank you. I used AsyncTask and it resolved the issue. Question, What if instead of trying to access a website, I wanted to retrieve some data from a file on my web server and used those data to create a chart of some sort in my application. Would you be able to assist or point me in the right direction? – Si8 Nov 04 '13 at 17:26
  • Glad I could be of assistance. You should create a separate question for your request if you need extensive help, or google it, but to get you started, you're probably looking at using something like HttpClient to make your request (http://developer.android.com/reference/org/apache/http/client/HttpClient.html) and grab a HttpResponse using the client's execute method. Happy coding ;-) – 2Dee Nov 04 '13 at 17:39
2

You must make request from nonUI thread, for example use AsyncTask or ? extends Thread

Aleksandr
  • 787
  • 6
  • 22
1

The problem, you are facing is that you are running your network code on the main thread, as the NetworkOnMainThreadException states.

Look at the answer to this question, for an explanation on how to use AsyncTask to avoid this situation: How to fix android.os.NetworkOnMainThreadException?

This blog post gives an in-depth explanation of the exception: http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html

And lastly, the official NetworkOnMainThreadException documentation can be found here: http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

Community
  • 1
  • 1
Mads Frandsen
  • 523
  • 4
  • 12
1

You are trying to get result from server directly from activity. This was allowed until 2.x. From Honeycomb onwards, NetworkOnMainThreadException was introduced. As this operation may take long time, it will block the UI thread, and will likely show ANR. For any time taking operation, a separate thread should be used.

You can use AsyncTask. It runs on separate thread from your activity.

In doInBackground() of AsyncTask, you can perform your desired operation and pass its result to onPostExecute() of this class based on which you can show the Toast message which you want to show in your application.

Nitish
  • 3,097
  • 13
  • 45
  • 80