尝试使用AsyncTask和Jsoup从URL获取文本

时间:2013-11-28 22:14:10

标签: java android android-asynctask html-parsing jsoup

网址只是文本文件,例如www.example.com/example.txt,所以我需要做的是从网站上获取整个文本。文本可以长达1MB。我不知道如何修改我的代码来执行此操作。

这是我的代码

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

我用new Title().execute();

来称呼它

此代码不起作用我无法获取文本。没有任何事情发生。

1 个答案:

答案 0 :(得分:0)

您应该做的是将所有元素添加到Elements对象。见下文:

@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;
}

然后是onPostExecute

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