0

I want to read the content of a URL with the following code :

        myUrl=new URL(url);
        stream=myUrl.openStream();

but the second line of code triggers an "android.os.NetworkOnMainThreadException" without any other explanation.

I work under Androïd 4 and I can add this code used to work with Androïd 2.3.3.

Any idea?

Thanks in advance for the time you will spend trying to help me.

Zelig63
  • 1,592
  • 1
  • 23
  • 40

3 Answers3

1

So problem is that application attempts to perform a networking operation on main thread and this is not allowed.

For your goal i recommend to you use AsyncTask and do your work in background Thread.

Here is example from my little app:

protected InputStream doInBackground(String... params) {

            int contentLength = 0;
            int buffLength = 0;
            int progress = 0;
            InputStream inputStream = null;
            try {

                URL url = new URL(params[0]);
                HttpURLConnection urlConntection = (HttpURLConnection) url.openConnection();
                urlConntection.setRequestMethod("GET");
                urlConntection.setAllowUserInteraction(false);
                urlConntection.setInstanceFollowRedirects(true);
                urlConntection.connect();
                if (urlConntection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    contentLength = urlConntection.getContentLength();
                    progressDialog.setMax(contentLength);
                    inputStream = urlConntection.getInputStream();

                    while ((buffLength = inputStream.read(MAX_BUFFER)) != -1) {
                        try {
                            Thread.sleep(1);
                            progress += buffLength;
                            DataTransmitted data = new DataTransmitted(progress, contentLength);
                            publishProgress(data);
                        }
                        catch (InterruptedException ex) {
                            Log.e(this.getClass().getName(), ex.getMessage());
                        }
                    }

                }
                else {
                    throw new IOException("No response.");
                }

            }
            catch (MalformedURLException ex) {
                Log.e(this.getClass().getName(), ex.getMessage());
            }
            catch (IOException ex) {
                errorDialog.show();
            }
            return inputStream;
        }

Or here is similar topic:

Community
  • 1
  • 1
Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106
1

From the Android developer's site:

A NetworkOnMainThreadException is thrown when an application attempts to perform a networking operation on its main thread.

You need to put your code in a separate thread or an AsyncTask.

Android versions 3.0 and above are much stricter about abuse against the UI Thread Read this article for more details

iTurki
  • 16,292
  • 20
  • 87
  • 132
1

You need to use AsyncTask now here's a quick example, i hope that will help you:

public class SimpleWebGrab extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    grabURL("http://android.com");
}

public void grabURL(String url) {
    new GrabURL().execute(url);
}

private class GrabURL extends AsyncTask<String, Void, Void> {
    private final HttpClient Client = new DefaultHttpClient();
    private String Content;
    private String Error = null;
    private ProgressDialog Dialog = new ProgressDialog(SimpleWebGrab.this);

    protected void onPreExecute() {
        Dialog.setMessage("Downloading source..");
        Dialog.show();
    }

    protected Void doInBackground(String... urls) {
        try {
            HttpGet httpget = new HttpGet(urls[0]);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            Content = Client.execute(httpget, responseHandler);
        } catch (ClientProtocolException e) {
            Error = e.getMessage();
            cancel(true);
        } catch (IOException e) {
            Error = e.getMessage();
            cancel(true);
        }

        return null;
    }

    protected void onPostExecute(Void unused) {
        Dialog.dismiss();
        if (Error != null) {
            Toast.makeText(SimpleWebGrab.this, Error, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(SimpleWebGrab.this, "Source: " + Content, Toast.LENGTH_LONG).show();
        }
    }

}
}

And please : call it Android, not Androïd it sounds french.

Tsunaze
  • 3,204
  • 7
  • 44
  • 81