我正在创建asynctask,retreive string data:
View.OnClickListener btnClk = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (btnGetData.getId() == ((Button) v).getId()) {
Object obj = new FetchTask(Main.this).execute((Integer) null);
}
}
};
我的任务:
public class FetchTask extends AsyncTask<Object, Object, Object> {
private Context ctx;
private String xml;
public FetchTask(Context context) {
ctx = context;
}
@Override
protected void onPreExecute() {
DialogDownload_Ring = ProgressDialog.show(Main.this, "Download...",
"Fetching XML data...");
DialogDownload_Ring.setCancelable(true);
DialogDownload_Ring.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
cancel(true);
}
});
super.onPreExecute();
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onPostExecute(Object result) {
if (result instanceof Exception) {
DialogDownload_Ring.setMessage("Download failed!");
} else {
DialogDownload_Ring.setMessage("Succesfully Downloaded!");
}
DialogDownload_Ring.dismiss();
super.onPostExecute(result);
}
@Override
protected Object doInBackground(Object... params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL_Local);
HttpResponse httpResponce = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponce.getEntity();
xml = EntityUtils.toString(httpEntity);
return xml;
} catch (Exception e) {
return e;
}
}
}
如何从Object obj中检索xml数据? obj.toString()不起作用。否则我创建asynctask字符串属性(扩展AsyncTask字符串,字符串,字符串)它正在工作,但进度条在retreive xml数据后启动,我也不明白。请帮帮我。 附:对不起我的英语不好......
答案 0 :(得分:3)
如果要在doInBackground
执行完成后在主ui线程中返回结果,则需要通过调用AsyncTask.get()方法执行AsyncTask,但这将冻结UI线程,直到doInBackground执行为止完成。您需要在线程内调用AsyncTask.get()
以避免UI冻结。启动AsyncTask
以便在UI线程中返回结果:
Object obj = new FetchTask(Main.this).execute((Integer) null).get();
第二种方法是在不调用AsyncTask.get
方法的情况下启动AsyncTask,并在onPostExecute
执行完成时以doInBackground
方法接收结果。
按下按钮启动AsyncTask:
new FetchTask(Main.this).execute((Integer) null);
以onPostExecute
获取结果:
@Override
protected void onPostExecute(Object result) {
// extract xml from result
super.onPostExecute(result);
}
答案 1 :(得分:0)
ASyncTask不能像这样工作:
Object obj = new FetchTask(Main.this).execute((Integer) null);
execute方法立即返回,任务在后台继续。
ASyncTask是异步的,所以这就是为什么它有onPostExecute
方法来完成它的工作。在解除对话之前或之后,将代码放到onPostExecute
中处理返回的项目(xml)。