AsyncTask and error handling on Android

前端 未结 12 2154
失恋的感觉
失恋的感觉 2020-11-27 10:32

I\'m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 11:01

    Create an AsyncResult object ( which you can also use in other projects)

    public class AsyncTaskResult {
        private T result;
        private Exception error;
    
        public T getResult() {
            return result;
        }
    
        public Exception getError() {
            return error;
        }
    
        public AsyncTaskResult(T result) {
            super();
            this.result = result;
        }
    
        public AsyncTaskResult(Exception error) {
            super();
            this.error = error;
        }
    }
    

    Return this object from your AsyncTask doInBackground methods and check it in the postExecute. ( You can use this class as a base class for your other async tasks )

    Below is a mockup of a task that gets a JSON response from the web server.

    AsyncTask> jsonLoader = new AsyncTask>() {
    
            @Override
            protected AsyncTaskResult doInBackground(
                    Object... params) {
                try {
                    // get your JSONObject from the server
                    return new AsyncTaskResult(your json object);
                } catch ( Exception anyError) {
                    return new AsyncTaskResult(anyError);
                }
            }
    
            protected void onPostExecute(AsyncTaskResult result) {
                if ( result.getError() != null ) {
                    // error handling here
                }  else if ( isCancelled()) {
                    // cancel handling here
                } else {
    
                    JSONObject realResult = result.getResult();
                    // result handling here
                }
            };
    
        }
    

提交回复
热议问题