Skip to content Skip to sidebar Skip to footer

Android: Handler For Asynctask

I use AsyncTask in combination with a ProgressDialog. See my code, I have a problem in onPostExecute. If the task is running for the first time it get a Null Poiter Exception for p

Solution 1:

Any reason why you need the Handler inside the AsyncTask? If you want to control your progress dialogue from an AsyncTask using a Handler is the correct way, however, your current Handler would get created and destroyed each time you start a new UpdateTask. If you define your handler outside your AsyncTask, something like:

privateHandlerhandler=newHandler(newHandler.Callback() {
    @OverridepublicbooleanhandleMessage(Message msg) {

    switch( msg.what ){
                case MSG:                       
                    progressDialog.show();
                    break;
                case DETACH:
                    progressDialog.dismiss();
                    break;  
            }

    returnfalse;
}
});

Now you can call handler.sendEmptyMessage(what) from any background thread safely, and the progressDialog will update on the UI thread only. Not a complete fix, and I don't know what int values you have defined for DETACH and MSG. But hopefully it will help. This is the method I use to update any UI element from a background task. Just do a bit more reading about the AsyncTask and updating UI elements.

Solution 2:

See https://stackoverflow.com/a/4538370/719212 And you should read about onPreExecute() in Android documentation.

Post a Comment for "Android: Handler For Asynctask"