【问题标题】:Android parse trouble HTML using Jsoup [duplicate]Android使用Jsoup解析麻烦的HTML [重复]
【发布时间】:2015-04-02 05:42:55
【问题描述】:

我们在 android studio 中使用 jsoup 解析实时 url 时遇到问题。相同的代码将在 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");

    }

如何解决这个问题并从实时 url 中获取标题?

【问题讨论】:

  • 也基于该问题的 cmets:你确定你在 android-studio 和 eclipse 中使用相同版本的 jsoup 吗?
  • 我正在使用相同版本的jsoup最新1.8.1.help e来解决这个问题

标签: java html parsing android-studio jsoup


【解决方案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();

【讨论】:

  • 它工作得很好,谢谢。
  • 希望你能得到答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 2013-09-21
  • 2011-03-11
  • 2011-08-18
  • 1970-01-01
相关资源
最近更新 更多