Search code examples
javaandroidandroid-asynctaskprogressdialog

How to change progressDialog text


I have an asynctask but if I implement a Thread.Sleep, then my app crashes, and I don't know why. In onPreExecute I can see my first message and then after two seconds it appears the other one I put in doInBackground, but it's not working.

private class sendMail extends AsyncTask<Void, Void, Void> {

        protected void onPreExecute() {
            dialog.setMessage("Please wait...");
            dialog.show();

        }

        // automatically done on worker thread (separate from UI thread)
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            dialog.setMessage("Downloading files...");

            new BackgroundTask().execute();

//MY DOWNLOADING METHODS STUFF

And then I dismiss this dialog somewhere else.

Log:

An error occurred while executing doInBackground()


Solution

  • You cannot access the UI elements from a background thread you can update the progressbar in onProgressUpdate, most importantly you need to publishProgress(value) in doInBackground and update using onProgressUpdate. Read more about the AsyncTask here.

    Example code:

    class MyTask extends AsyncTask<Integer, Integer, String> {
            @Override
            protected String doInBackground(Integer... params) {
                for (; count <= params[0]; count++) {
                    try {
                        Thread.sleep(1000);
                        publishProgress(count);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return "Task Completed.";
            }
            @Override
            protected void onPostExecute(String result) {
                progressBar.setVisibility(View.GONE);
                    txt.setText(result);
                    btn.setText("Restart");
            }
            @Override
            protected void onPreExecute() {
                txt.setText("Task Starting...");
            }
            @Override
            protected void onProgressUpdate(Integer... values) {
                txt.setText("Running..."+ values[0]);
                progressBar.setMessage("Downloading files...");
                progressBar.setProgress(values[0]);
            }
        }