Android,等待对话框根本没有显示

时间:2012-03-06 20:56:06

标签: android dialog

我想显示等待对话但它根本没有显示,这很奇怪,因为需要花费大量时间的东西是setData()函数,我得到一个json feed并将它们保存在数据库中(需要3/5秒。)

这是我的代码:

    ProgressDialog dialog = ProgressDialog.show(TabLayoutActivity.this, "", "Loading. Please wait...", true);

    //refresh the view
    taskLiteApplication.setData();

    //change view
    Intent myIntent = new Intent(TabLayoutActivity.this, TabLayoutActivity.class);
    TabLayoutActivity.this.startActivity(myIntent);

    //kill the dialog waiting
    dialog.cancel();

2 个答案:

答案 0 :(得分:2)

我敢打赌,问题在于您正在UI线程上完成所有这些工作,所以当您启动对话框时,启动并显示窗口的线程实际上在您执行setData()时冻结工作。你真的应该将setData函数移动到后台线程或AsyncTask,以便在后台执行大量工作时UI线程可以继续。

private ProgressDialog dialog;

void doStuff()
{
    dialog = ProgressDialog.show(TabLayoutActivity.this, "", "Loading. Please wait...", true);
    HeavyTask task = new HeavyTask();
    task.execute();
}

private class HeavyTask extends AsyncTask<Void, Void, Void> {
     protected Void doInBackground(Void... args) {
         //refresh the view
         taskLiteApplication.setData();
         return;
     }

     protected void onPostExecute(Void results) {
         //change view
         Intent myIntent = new Intent(TabLayoutActivity.this, TabLayoutActivity.class);
         TabLayoutActivity.this.startActivity(myIntent);

         //kill the dialog waiting
         dialog.dismiss();
         dialog = null;
     }
 }

答案 1 :(得分:0)

我在猜测taskLiteApplication.setData();正在UI线程而不是后台线程中运行,或者它在后台线程中运行并且正在调用取消,因为它在UI线程中取消。

解决问题的基本线程:

private ProgressDialog dialog; // Keep this global
private Handler mHandler;

void doStuff() {
    dialog = ProgressDialog.show(TabLayoutActivity.this, "", "Loading. Please wait...",  true);
    mHandler = new Handler()
    {
        @Override public void handleMessage(Message msg) {
            if (msg.obj != null) {
                dialog.dismiss();
                //change view
                Intent myIntent = new Intent(TabLayoutActivity.this, TabLayoutActivity.class);
                TabLayoutActivity.this.startActivity(myIntent);
            }
        }
    };
    //refresh the view
    Thread t = new Thread(new Runnable() {
        @Override public void run() {
            // Assuming setData does NOT run on it's own background thread
            taskLiteApplication.setData();
            Message message = Message.obtain();
            message.obj = "DONERAEREAR";
            mHandler.sendMessage(message);
        }
    })};
    t.start();
}

编辑添加了一个处理程序,正如Wizetux所指出的那样,对话框需要在UI线程中取消

这样做的好处是您可以发送处理程序错误消息,警告消息,成功消息并相应地处理。

E.G。

message.obj = "ERROR";
mHandler.sendMessage(message);

然后在处理程序

if ((String)msg.obj.equals("ERROR")) { /* Handle Error */ }