Android JSoup使应用程序崩溃

时间:2013-08-20 10:19:46

标签: java android jsoup

当我打开应用程序时,我收到消息"应用程序停止"。可能是什么原因?

主要班级:

public class MainActivity extends Activity {

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); // Always call super.onCreate() first.
        setContentView(R.layout.activity_main); // Then load the layout.

        // Find textView3 in layout and set it's text to HTML code.
        // There's no need to create a new TextView() here.
        TextView textView = (TextView) findViewById(R.id.textView1);
        textView.setText(getHtmlCode());
      }

      // Structure your code. If it's a larger block that does one thing,
      // extract it into a method.
      private String getHtmlCode() {
        try {
          Document doc = Jsoup.connect("http://www.example.com/").get();
          Element content = doc.select("a").first();
         // return content.text();
          return "kktt";
        } catch (IOException e) {
          Toast.makeText(this, "Failed to load HTML code",
              Toast.LENGTH_SHORT).show();
          return "kk";
        }
      }
    }

////Elements divs = doc.select("div#test");   //select all the content of the div tags with the id attribute set to test

*我将jar添加到库

2 个答案:

答案 0 :(得分:0)

将getHtmlCode()移入AsyncTask。您不应该对onCreate()方法或主线程执行网络操作。所以将代码移动到AsyncTask。并且可以在AsyncTask中更新UI。

答案 1 :(得分:0)

您需要获得Android清单文件的以下权限。

<uses-permission android:name="android.permission.INTERNET" />

添加上述权限后,您需要将方法getHtmlCode()中的代码移动到异步任务或线程。在那之后你很高兴。