I have an action with a button that launches a lengthy task. I am executing a task using AsyncTask and showing a specific ProgressBar, which is updated as the task progresses. Everything works fine at the first start of the task, but on subsequent launches a dialog box appears, but it is already 100% and 100/100. I redefine both onCreateDialog and onPrepareDialog in my activity. I assumed that using setProgress (0) would reset the dialog box, but this does not work. I use showDialog in the AsyncTask onPreExecute method and disable Dialog in AsyncTask onPostExecute. The only way I was able to get the reset dialog is to use removeDialog in onPostExecute, but I would prefer not to recreate the dialog since I am going to reuse it several times. The corresponding code is given below. This is at API level 10.
@Override protected Dialog onCreateDialog(int id) { switch (id) { case PROGRESS_DIALOG: progressDialog = new ProgressDialog(ProtoBufSerializationTestActivity.this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setCancelable(true); progressDialog.setMax(100); progressDialog.setMessage("Testing..."); return progressDialog; default: return null; } } @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); switch (id) { case PROGRESS_DIALOG: ProgressDialog tmp = (ProgressDialog)dialog; tmp.setProgress(0); tmp.setSecondaryProgress(0); return; default: Log.e("test", "Unknown dialog requested"); } } private class SerializationTestTask extends AsyncTask<Void, Integer, Long> { @Override protected void onPreExecute() { showDialog(PROGRESS_DIALOG); } @Override protected Long doInBackground(Void... params) { long accumulator = 0; int totalSize = 0; for (int i = 0; i < 10000; i++) { final long start = System.nanoTime();
Change After accepting the @Arhimed offer, I got the following code. It is much simpler. I could use DialogFragment , but I don't think it is necessary in this case.
private class SerializationTestTask extends AsyncTask<Void, Integer, Long> { private ProgressDialog dialog; @Override protected void onPreExecute() { dialog = ProgressDialog.show(ProtoBufSerializationTestActivity.this, "Serialization Test", "Testing...", false); } @Override protected Long doInBackground(Void... params) { long accumulator = 0; int totalSize = 0; for (int i = 0; i < 10000; i++) { final long start = System.nanoTime();
source share