0

我是 Android 新手,正在练习创建进度对话框。我想每隔几秒钟更改一次对话框中的消息,但是当我更改消息时我的应用程序崩溃了。有什么想法我可能做错了吗?

private void progressDialogTest(final ArrayList<String> messages)
    {
        AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() 
        {
            private ProgressDialog progressDialog;

            @Override
            protected void onPreExecute() 
            {
                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setTitle("Progress Dialog");
                progressDialog.show();
            }

            @Override
            protected Void doInBackground(Void... arg0) 
            {
                try 
                {
                    for(int i=0; i<messages.size(); i++)
                    {
/******** APPLICATION SEEMS TO CRASH AT LINE BELOW ********/
                        progressDialog.setMessage(messages.get(i));
                        Thread.sleep(3000);
                    }
                } 
                catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) 
            {
                progressDialog.dismiss();
            }
        };
        task.execute((Void[])null);
    }

在此处输入图像描述

4

1 回答 1

5

将代码移至 onProgressUpdate,例如:

@Override
protected void onProgressUpdate(Integer... progress) {
    super.onProgressUpdate(progress);
    progressDialog.setMessage(messages.get(progress[0]));
}

@Override
protected void doInBackground(Void... arg0) {
    /* ... */

    //progressDialog.setMessage(messages.get(i)); Change this line to
    publishProgress(i);

    /* ... */
}
于 2013-06-18T02:39:54.337 回答