制作HTTP请求时ProgressDialog未显示

3
我希望在进行http连接请求时能显示进度对话框。 这里有一个请求方法。
protected Result request(String urlStr, String postData) {
    ProgressDialog dialog = ProgressDialog.show(activity, "", "Loading...",true);
    Result result = new Result();
    String message = "";
    try {
        message = HttpRequest.postURL(urlStr, postData);
        result = new Result(message);
    } catch (Exception e) {
        Log.e(TAG,"Failed to request data from " + urlStr + "\n" + e.getMessage());
    }
    dialog.dismiss();
    return result;
}

但是当这个方法运行时,ProgressDialog没有显示出来。如何解决这个问题?

可能是ProgressDialog not showing while performing a task的重复问题。 - Sufian
3个回答

2
您需要调用dialog.show()
启动对话框并在屏幕上显示。该窗口位于应用程序层并且是不透明的。请注意,当显示对话框时,您不应覆盖此方法以进行初始化,而是应在onStart()中实现。
另外,我建议您在AsyncTask类的doInBackground()中执行此操作。 在onPreExecute()中,显示ProgressDialog,并在onPostExecute()中取消它的显示。

伙计,我非常确定ProgressDialog.show会调用dialog.show(),我在源代码中看到了。 - Joe
我无法弄清楚如何在AsyncTask中返回结果。我认为这个请求必须是同步的。 - Joe
这要看情况。你可以将 AsyncTask 设为内部类。 - An SO User

0
protected Result request(String urlStr, String postData) {
    ProgressDialog dialog = ProgressDialog.show(activity, "", "Loading...",true);
    Result result = new Result();
    String message = "";
    try {
        message = HttpRequest.postURL(urlStr, postData);
        result = new Result(message);
    } catch (Exception e) {
        Log.e(TAG,"Failed to request data from " + urlStr + "\n" + e.getMessage());
    }
    dialog.show();
    return result;
}

别忘了在按钮中调用dialog.dismiss();


0

进度对话框无法显示的原因有很多,但在您的情况下,我猜测是因为您将错误的Context传递给了ProgessDialog,请检查您的Activity上下文。确保您使用适当的Context或将其更改为ApplicationContext

ProgressDialog dialog = ProgressDialog.show(activity, "", "Loading...",true);

请检查这行代码,特别是activity。希望这可以帮到你。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接