Is there a specific way to handle failure in an AsyncTask? As far as I can tell the only way is with the return value of task. I\'d like to be able to provide more details o
What I always do is create a new Object (you can call it AsyncTaskResult or whatever you like) that can get returned with doInBackground. This Object would have two things:
I would then return this object to postExecute() and let that method check for the error, if there is then I handle it accordingly, otherwise I take the expected result and do whatever with it.
The object would be something like:
public class AsyncTaskResult {
Exception exception;
T asyncTaskResult;
public void setResult(T asyncTaskResult) {
this.asyncTaskResult = asyncTaskResult;
}
public T getResult() {
return asyncTaskResult;
}
public void setException(Exception exception) {
this.exception = exception;
}
public boolean hasException() {
return exception != null;
}
public Exception getException() {
return exception;
}
}
And your code becomes :
/** this would be cool if it existed */
protected void onError(Exception ex) {
// handle error...
}
@Override
protected AsyncTaskResult doInBackground(String... params) {
AsyncTaskResult result = new AsyncTaskResult();
try {
// ... download ...
} catch (IOException e) {
result.setException(e);
}
return result;
}
@Override
protected void onPostExecute(AsyncTaskResult result) {
if(result.hasException()) {
// handle error here...
onError(result.getException());
} else {
// deal with the result
}
}