Android: Handler for AsyncTask

后端 未结 2 898
情话喂你
情话喂你 2021-01-25 11:59

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 fo

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-25 12:12

    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:

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
    public boolean handleMessage(Message msg) {
    
        switch( msg.what ){
                    case MSG:                       
                        progressDialog.show();
                        break;
                    case DETACH:
                        progressDialog.dismiss();
                        break;  
                }
    
        return false;
    }
    });
    

    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.

提交回复
热议问题