gpt4 book ai didi

android - 使用 Android AsyncTask 下载 html 文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:59:40 24 4
gpt4 key购买 nike

我刚开始使用 android,我正在开发一个应该下载 html 文件内容的简单应用程序。我正在按照建议使用 AsyncTask,但我遇到了一个问题。在下面的代码中(我遵循了教程代码),我得到 tv cannot be resolved 用于 onPostExecute 方法。如何访问下载的文件?谢谢:

public class FlashResults extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
setContentView(tv);
readWebpage(tv);
}


protected class DownloadPage extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {

String responseStr = null;

try {
for (String url : urls) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(get);
HttpEntity httpEntity = httpResponse.getEntity();
responseStr = EntityUtils.toString(httpEntity);
}
} catch (UnsupportedEncodingException e) {

} catch (ClientProtocolException e) {

} catch (IOException e) {

}
return responseStr;
}

protected void onPostExecute(String result) {
tv.setText(result);
}
}

public void readWebpage(View v) {
DownloadPage task = new DownloadPage();
task.execute(new String[] { "http://seznam.cz" });
}

最佳答案

到目前为止建议的所有其他答案都可以。但是,我会添加一些其他注释:

  1. 如果您只访问 TextView tv在此 onCreate 和 DownloadPage Activity 中,您可以限制对 tv 的访问通过直接将其提供给 DownloadPage 的构造函数
  2. 对于像 DownloadPage AsyncTask 这样有用的东西,我通常将它从任何 Activity 的内部类中删除,而是将其放在一个名为“Utils”的公共(public)类中,许多其他 Activity 可以根据需要使用它。 (代码模块化)
  3. 如果你打算使用一个内部类(完全合法),那么做它总是好的做法privatestatic对于你正在做的事情。

像这样:

public class FlashResults extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
setContentView(tv);
readWebpage(tv);
}

public void readWebpage(View v) {
DownloadPage task = new DownloadPage(tv);
task.execute(new String[] { "http://seznam.cz" });
}

private static class DownloadPage extends AsyncTask<String, Void, String> {

private TextView textView;
public DownloadPage(TextView tv){
textView = tv;
}

protected String doInBackground(String... urls) {

String responseStr = null;

try {
for (String url : urls) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(get);
HttpEntity httpEntity = httpResponse.getEntity();
responseStr = EntityUtils.toString(httpEntity);
}
} catch (UnsupportedEncodingException e) {

} catch (ClientProtocolException e) {

} catch (IOException e) {

}
return responseStr;
}

protected void onPostExecute(String result) {
if (textView != null) {
textView.setText(result);
}
}
}
}

关于android - 使用 Android AsyncTask 下载 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13347662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com