Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jsoup.connect() working with Java, not with Android

Tags:

android

jsoup

I've tried the Jsoup.connect() example given on the Jsoup website and it works fine in Java.

For some reason, I can't make it work in Android Projects (Eclipse) even though I allow the Internet access permission in my AndroidManifest. The Jsoup library is installed correctly and I can work with Jsoup.parse() without any issues. Here's a few line of codes of what works in Java and also the permission in AndroidManifest.

Java

public static void main(String[] args){
    Document doc;
    try {
        doc = Jsoup.connect("http://google.ca/").get();
        String title = doc.title();
        System.out.print(title);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

AndroidManifest.xml

<uses-sdk android:minSdkVersion="12" />
<uses-permission android:name="android.permission.INTERNET"/>
<application

When I try to run it, it crashes and the log says:

01-09 20:19:30.560: E/AndroidRuntime(26839): java.lang.RuntimeException: 
Unable to start activity 
ComponentInfo{com.mrdroidinator.com/com.mrdroidinator.com.Parselhjmq}: android.os.NetworkOnMainThreadException
like image 272
user1139012 Avatar asked Jan 09 '12 15:01

user1139012


1 Answers

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

The problem is that you are performing a network operation on the main thread, which is prohibited in API level 11+. This is because if you do it the UI is "frozen" until the document finishes downloading, so it is needed to perform such operations on a different thread, which doesn't affect UI perfomance.

This is how you start a new thread:

Thread downloadThread = new Thread() {
  public void run() {
    Document doc;
    try {
      doc = Jsoup.connect("http://google.ca/").get();
      String title = doc.title();
          System.out.print(title);
    } catch (IOException e) {
          e.printStackTrace();
    }
  }
};
downloadThread.start();
like image 170
packito Avatar answered Sep 17 '22 22:09

packito