我剛剛開始使用android,我正在開發一個應該下載html文件內容的簡單應用程序。我建議使用AsyncTask,但我遇到了一個問題。在下面的代碼(我跟着一個教程代碼),我得到tv cannot be resolved
爲onPostExecute
方法。如何訪問下載的文件?謝謝:使用Android AsyncTask下載html文件
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" });
}
}
方面的問題。 tv是在onCreate中聲明的局部變量(因此只能從那裏訪問)。使其成爲實例字段 – njzk2