0

I was trying to write some codes that takes in a url from the user and after which when the submit button is clicked, I will take the url and make a call and retrieve the html source code from the page. However, I have gotten a exception of the following:

W/System.err(14858): android.os.NetworkOnMainThreadException W/System.err(14858): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)

It seems that for android 3.0 the platform that I am trying to development on doesn't allow me to use the network resources on the main method. I understand that there are methods such as running it in the background or use the async method should work, but can anyone guide me on this? I'm not too sure on how to go about it. I'm new to programming. Thanks in advance.

Below is my current code, on the onclick method:

    String htmlCode = ""; 

    try {
    URL url = new URL("http://www.google.com");
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

    String inputLine;

    while ((inputLine = in.readLine()) != null) {
        htmlCode += inputLine;
        Log.d(LOG_TAG, "html: " + inputLine);
    }

    in.close();
    } catch (Exception e) {
        e.printStackTrace();
        Log.d(LOG_TAG, "Error: " + e.getMessage());
        Log.d(LOG_TAG, "HTML CODE: " + htmlCode);
    }

1 Answer 1

1

You could use a Runnable or Thread, but probably the most idiomatic Android way to do this is to use an AsyncTask.

new AsyncTask<String, Void, String>(){
  @Override
  protected String doInBackground(String... urlStr){
    // do stuff on non-UI thread
    StringBuffer htmlCode = new StringBuffer();
    try{
      URL url = new URL(urlStr[0]);
      BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

      String inputLine;

      while ((inputLine = in.readLine()) != null) {
        htmlCode += inputLine;
        Log.d(LOG_TAG, "html: " + inputLine);
      }

      in.close();
    } catch (Exception e) {
        e.printStackTrace();
        Log.d(LOG_TAG, "Error: " + e.getMessage());
        Log.d(LOG_TAG, "HTML CODE: " + htmlCode);
    }
    return htmlCode.toString();
  }         

  @Override
  protected void onPostExecute(String htmlCode){
    // do stuff on UI thread with the html
    TextView out = (TextView) findViewById(R.id.out);
    out.setText(htmlCode);
  }
}.execute("http://www.google.com");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.