我试图创建一个 AsyncTask 以从服务器端获取一些数据。但它在行“IOUtils.copy((response_.getEntity().getContent()), writer);”中的 onPostExecute() 中报告了空指针异常。我使用一些日志来查看发生了什么,发现打印了日志 1 和 3,但没有打印日志 2。为什么 onPostExecute 在 client.executed() 完成之前执行?谁能给些建议?
private class GetForm extends AsyncTask<String, Integer, Object> {
private HttpResponse response_;
private Exception exception_;
private String url_;
public GetForm(String url) {
super();
url_ = url;
}
protected Object doInBackground(String... params) {
try {
Log.i("mylog","inside doInbackground 1.");
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url_);
response_ = client.execute(request);
Log.i("mylog","inside doInbackground 2.");
} catch (Exception e) {
exception_ = e;
}
return response_;
}
@Override
protected void onPostExecute(Object o) {
// Your current UI stuff here.
Log.i("mylog","inside onPostExecute 3.");
StringWriter writer = new StringWriter();
try{
IOUtils.copy((response_.getEntity().getContent()), writer);
......
}catch(IOException e) {
e.printStackTrace();
}
}
}
最佳答案
onPostExecute() 不太可能先被调用,更有可能是在您的 doInBackground() 中抛出了异常……以及为什么没有打印 Log 2。检查 LogCat 中的警告或调试页面。此外,您应该分别打印这两个异常。
关于android - 为什么 onPostExecute 在 AsyncTask 中的 doInBackground 完成之前执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12869795/