【发布时间】:2015-06-19 12:51:08
【问题描述】:
我正在使用AsyncTask 发出JSON HTTP 请求。我在onPreExecute() 中创建了一个ProgressDialog,我在onPostExecute() 中将其关闭。问题是,diInBackground() 中有一条 Toast 消息,它显示 JSON response 和 ProgressDialog 在 Toast 出现之前被解除,这意味着 onPostExecute() 在生成 Toast 之前被调用。如何在 Toast 出现之前将其关闭?
这是我的代码。
private class login extends AsyncTask<Void,Void,Void>{
private ProgressDialog progressDialog;
@Override
protected void onPreExecute(){
super.onPreExecute();
// Create & Start Progress Dialog
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
String url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk";
JsonObjectRequest req = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
Toast.makeText(getApplicationContext(),response.toString() , Toast.LENGTH_SHORT).show();
}
}
catch (Exception e){
Toast.makeText(getApplicationContext(),"Server error!..",Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("from on error response Server Error..: ", error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(req);
return null;
}
@Override
protected void onPostExecute(Void v){
// Terminate Progress Dialog
progressDialog.dismiss();
}
}
【问题讨论】:
-
如何从后台线程调用 Toast ?我认为这段代码是错误的。
-
好的。但是如何从 onPostExecute() 访问响应对象?在 doInBackground() 完成后不再可以访问它。 (我需要将 Result 设置为 JSONObject 吗?)
标签: android json android-asynctask progressdialog