1

i'm trying to do use a JSOUP HTML parsing library to get a HTML document using

Document doc = Jsoup.parse(u, 1000);

and i'm getting the error "android.os.NetworkOnMainThreadException"

I understand its because I need to have the download occurring somewhere other than the main thread but I don't understand how to fix this.

If I use threading I need to be able to return doc so I can parse through when the download is finished.

Can you help me fix this?

The class I am using is as follows:

public class DataSorter{

   private Document doc;
   DataSorter(){
      downloadData();
   }
   private void downloadData() throws IOException{
        String url = "www.google.com";
        URL u = new URL(url);
        System.out.println("Downloading....");
        doc = Jsoup.parse(u, 5000); //Time out 5000ms
        System.out.println("Download Successful");
   }
   Document getDoc(){
      return doc;
   }
}
Eduardo
  • 6,900
  • 17
  • 77
  • 121

3 Answers3

2

You are doing a Network Related operation on the main ui thread. use a Thread or AsyncTask

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

AsyncTask docs

http://developer.android.com/reference/android/os/AsyncTask.html

A similar post @

How to fix android.os.NetworkOnMainThreadException?

You can use a Thread but remember you can update ui on the ui thread and not on the background thread.

You can use AsyncTask use onPreExecute and onPostExecute to update ui. Use doInbackground to do your network related operaion.

Move this

   Document doc = Jsoup.parse(u, 1000);

inside a Thread or doInbackground of AsyncTask.

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
2

use an asynctask and return the doc to the onPostExecute

see this link about an asynctask

AsyncTask Android example

Community
  • 1
  • 1
tyczj
  • 71,600
  • 54
  • 194
  • 296
1
android.os.NetworkOnMainThreadException

because you are performing network operations in main UI thread

ether use AsyncTask or a Thread

reference for AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html

Tarsem Singh
  • 14,139
  • 7
  • 51
  • 71