Search code examples
javaandroidhtmlweb-testing

Downloading html source code and loading it


I found this code from here download html source android? . But when I try running it, my program keeps crashing. I have already added the internet permission in. Any ideas?

Edit: Here is the full error message. 08-02 00:16:47.364: E/EmbeddedLogger(1577): Error getting package label: com.jimmyc.lawrenceh.schedulinglookup

Edit2: It works on Android 2.2 but it doesn't work on Android 4.0/3.0.

 private void initialize() {
      //initialize variables here
      try {
          getHtml();
      }
      catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
    }

    public void getHtml() throws ClientProtocolException, IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet("http://www.yahoo.com");
        HttpResponse response = httpClient.execute(httpGet, localContext);
        String result = "";

        BufferedReader reader = 
            new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = null;
        while ((line = reader.readLine()) != null){
            result += line + "\n";
            // Toast.makeText(Connect.this, line.toString(), Toast.LENGTH_LONG).show();

        }
    }

Solution

  • I think you are trying to download the HTML code in the UI Thread. Try to download it in the background, using AsynkTask

    Edit. If you say that it works on Android 2.2 but it doesn't work on Android 4.0/3.0 I'm completely sure you are trying to download it in the UI thread. From Android 3.0, you can't do long process in the UI thread because you can block it. You must do the download in a different thread