Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

android - Parsing with jsoup throws error (NetworkOnMainThreadException)

I downloaded the jsoup library jsoup-1.7.1.jar core and imported it to my project using the Project -> Properties->Java Build Path -> Add external Jars and I pasted the library file to my libs folder. However there seems to be some problem about importing the Jsoup library to my project. When I run my app, upon launching I get this error.

12-26 22:59:24.133: E/AndroidRuntime(6710): FATAL EXCEPTION: main
12-26 22:59:24.133: E/AndroidRuntime(6710): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsouptest/com.example.jsouptest.MainActivity}: android.os.NetworkOnMainThreadException

After searching and asking I found out that eclipse sees the jsoup.jar, but unable to package it to APK file for the app to run. I tried to organize Imports by pressing Shift+Alt+O and I would get the same error. At this point, I am unsure about what is wrong and have no idea how to fix it. I have only hope someone will lead me toward the solution. Appreciate your time!

This is my code:

package com.example.jsouptest;

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         Document doc;
         try {
             doc = Jsoup.connect("http://google.com/").get();
             String title = doc.title();
          System.out.print(title);
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have a

android.os.NetworkOnMainThreadException

Which has nothing to do with your jar working properly or not.

The Exception is thrown by the new versions of Android so that you don't lock the UI Thread (which is the main Thread) doing network operations.

Use an AsyncTask (simple explanation about what each part of the AsyncTask does can be found here)or another Thread for network stuff. An Asynctask is easier to work with if you need to update the UI once the background work completes.

An example of an AsyncTask with your code base can be:

private class MyTask extends AsyncTask<Void, Void, String> {

  @Override
  protected String doInBackground(Void... params) {
    String title ="";
    Document doc;
    try {
      doc = Jsoup.connect("http://google.com/").get();
      title = doc.title();
      System.out.print(title);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return title;   
  } 


  @Override
  protected void onPostExecute(String result) {        
    //if you had a ui element, you could display the title
    ((TextView)findViewById (R.id.myTextView)).setText (result);
  }
}

I assume:

  • The task is an inner class in your Activity.
  • You are forwarding the title gotten to a UI Element (eg a TextView) since that's what AsyncTasks are usually used for.

To call the AsyncTask, put this after setContentView(R.layout.activity_main);

new MyTask().execute();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...