我是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);
}
答案 0 :(得分:6)
将代码移至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);
/* ... */
}