简体   繁体   中英

How to get HTML content using class name?

I'm trying to create a class which uses the jsoup library to make an object of elements from a website.
After reading the documentation, this is what I have:

public class storyObj {
public String title;
public String preview;
public String date;
String url = "http//:davisclipper.com";
Bitmap bitmap;

private class Title extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        try {
            Document doc = Jsoup.connect(url).get();
            Elements storyTitle = doc.getElementsByClass("story_item_title");
            title = storyTitle.attr("content");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

public String getTitle(){
    return title;
}

In my main activity I set a TextView to get the returned title:

storyObj story = new storyObj();
String text = story.getTitle();

TextView title = (TextView) findViewById(R.id.main_title);
title.setText(text);

All I get is an empty string.

You seem to be misunderstanding how threads work. The Jsoup happens in the background. Meanwhile, you're continuing on the main thread with setting the text, which you're not guaranteed to have

You need to move the async task into the activity.

And you need to implement a onPostExecute for it where you will title.setText(text);

You also need to make the doInBackground return title

Like so

this.title = (TextView) findViewById(R.id.main_title);

new AsyncTask<Void, Void, String>() {
    @Override
    protected String doInBackground(Void... params) {
        try {
            Document doc = Jsoup.connect(url).get();
            Elements storyTitle = doc.getElementsByClass("story_item_title");
            return storyTitle.attr("content");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override 
    public void onPostExecute(String content) {
        MainActivity.this.title.setText(content);
    } 
}.execute();

Unless this website is dynamically generated by Javascript, Jsoup is the wrong library though. Not sure if a locals news site is that advanced, though

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM