【发布时间】:2020-01-14 15:45:55
【问题描述】:
我有一个名为 JsonHandler 的类,它带有异步任务来连接到 api 并获取 json 内容。它用于某些活动,但我无法显示警报对话框“正在加载...请稍候”你能帮我解决这个问题吗?
public class JsonHandler extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
JsonHandler(Context context)
{
this.context = context;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Wait");
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setMessage("Loading please wait...");
alertDialog.show();
}
@Override
protected String doInBackground(String... urls) {
//Here program is connecting to api and return needed strings
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
alertDialog.dismiss();
//Toast.makeText(context, "Update Successful", Toast.LENGTH_SHORT).show();
}
在主要活动中:
jsonResponse = new JsonHandler(this)
.execute("allowedVersion").get();
当我在 onPostExecute 中使用 alertDialog.show() 时,它会显示但为时已晚..
【问题讨论】:
-
你可以试试这个方法,像你做的那样让警告对话框成为一个全局变量,将alertdialog代码添加到onCreate,然后使用alertdialog.show();在 onPreExecute 然后 alertdialog.dismiss();在 onPostExecute
-
迈克,如果我要评论驳回它会显示,但我仍然认为它不能正常工作。当我点击按钮 [Check] 时,我可以看到很少的 Freeze,而不是看到 alertDialog。我认为为时已晚:/。在 doInBackground 我正在使用 URLConnection,也许这会产生问题?看起来 onPreExecute 在 doInBackround 完成时有效:/
标签: java android json asynchronous