简体   繁体   中英

Trying to get text from an url with AsyncTask and Jsoup

The urls are just text files like www.example.com/example.txt so what I need to do is get the whole text from the website. The text can be very long up to 1MB. I dont know how I should modify my code to do this.

Here is my code

private class Title extends AsyncTask<Void, Void, Void> {
    String text;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(Story.this);
        progressDialog.setMessage("Loading");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            Document document = Jsoup.connect(url).get();              
            text = document.text();    //I made this part up. Definitely WRONG
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        story.add(text);        //story is an array
        progressDialog.dismiss();
    }
}

I call it with new Title().execute();

This code doesn't work I cant get the text. Nothing happens.

What you should be doing is adding all of the Elements to an Elements object. See below:

@Override
protected Void doInBackground(Void... params) {
    try {
        Document document = Jsoup.connect(url).get();              
    } catch (IOException e) {
        e.printStackTrace();
    }
    Elements elem = null; 
    elem = document.select("*");
    Log.i("Value of elem", String.valueOf(elem);
    return null;
}

Then for your onPostExecute :

@Override
protected void onPostExecute(Void result) {
    String valueofelement = elem.text();
    story.add(valueofelement);        //story is an array
    progressDialog.dismiss();
   }
}

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