Skip to content Skip to sidebar Skip to footer

AsyncTask Crashes Sometimes

One of my main AsyncTasks seems to be crashing occasionally (the progress bar freezes and the process stops) and I wondered if I was doing something wrong in my code. It looks like

Solution 1:

You can't manipulate the UI from other threads. And I see that you are calling mProgressBar.setMax(delayTime - 1); inside the doInBackground() method, which is executed in a background thread. This will cause problems. You have to move this code inside onPreExecute() or other method.


Solution 2:

The method doInBackground of AsyncTask is executed in a separated Thread. onPreExecute and onPostExecute methods are executed in UI Thread. You can manipulate UI elements only if you are on the UI Thread. If you want to manipulate UI from AsyncTask.doInBackground, you have to use runOnUiThread method:

@Override
protected Boolean doInBackground(Integer... params) {
    int delayTime = params[0];

    runOnUiTread(new Runnable() {
        @Override
        public void run() {
            mProgressBar.setMax(delayTime - 1);
        }
    });

    for (int i = 0; i < delayTime; i++) {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            Log.e(DEBUG_TAG, "Can't sleep thread");
        }
        if (mPause) {
            i--;
        } else {
            publishProgress(1);
        }
    }
    return true;
}

The runOnUiThread() is a method of the Activity class. You can use it as I writed only if you declare the AsyncTask class inside your Activity. If it is declared out from Activity class, you can pass a reference to the Activity in the constructor of the AsyncTask, for using it to call runOnUiThread()

public class MyAsyncTask extends AsyncTask {
    Activity a;

    public MyAsyncTask(Activity a) {
        this.a = a;
    }

    ...

    @Override
    protected Boolean doInBackground(Integer... params) {
        int delayTime = params[0];

        a.runOnUiTread(new Runnable() {
            @Override
            public void run() {
                mProgressBar.setMax(delayTime - 1);
            }
        });

        ...
    }

    ...
}

Solution 3:

I think the problem here (apart from trying to manipulate UI from non-main thread, which is of course wrong) lays in Samsung S2 device: please look at this.


Post a Comment for "AsyncTask Crashes Sometimes"