Android parse trouble HTML using Jsoup [duplicate]

2019-09-02 05:43发布

This question already has an answer here:

we get trouble parsing live url using jsoup in android studio.the same code will be working in eclipse.we got the error

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

here my activity code

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");

    }

how to solve this issue and get the title from the live url?

1条回答
Rolldiameter
2楼-- · 2019-09-02 06:24

you can use AsyncTask class to avoid NetworkOnMainThreadException here you can try this code.

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();
    }
}

}

and add your mainActivity this

new FetchWebsiteData().execute();
查看更多
登录 后发表回答