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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With