Android使用Jsoup解析HTML问题

时间:2015-04-02 05:42:55

标签: java html parsing android-studio jsoup

我们在android studio中使用jsoup解析实时网址时遇到问题。相同的代码将在eclipse中运行。我们得到了错误

Method threw 'java.lang.NullPointerException' exception.can not evaluate org.jsoup.parser.HtmlTreebuilder.tostring()

这是我的活动代码

String title=null;
    Document document;
    try {
        document= Jsoup.connect("https://www.facebook.com/")
                .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                .referrer("http://www.google.com")
                .get();
        title=document.title();
        TextView text=(TextView)findViewById(R.id.textView);
        text.setText(title);

    } catch (Exception e) {
        e.printStackTrace();
        Log.d("tag","document");

    }

如何解决此问题并从实时网址获取标题?

1 个答案:

答案 0 :(得分:1)

您可以使用AsyncTask课程来避免NetworkOnMainThreadException 在这里你可以试试这段代码。

private class FetchWebsiteData extends AsyncTask<Void, Void, Void> {
    String websiteTitle, websiteDescription;

    @Override
    protected void onPreExecute() {
        //progress dialog
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            // Connect to website
            Document document = Jsoup.connect(URL).get();
            // Get the html document title
            websiteTitle = document.title();
            Elements description = document.select("meta[name=description]");
            // Locate the content attribute
            websiteDescription = description.attr("content");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // Set title into TextView
        TextView txttitle = (TextView) findViewById(R.id.txtData);
        txttitle.setText(websiteTitle + "\n" + websiteDescription);
        mProgressDialog.dismiss();
    }
}

}

并添加你的mainActivity

new FetchWebsiteData().execute();