Tôi muốn bắt ngoại lệ một chuỗi trong doInBackground và in thông báo lỗi trong onPostExcecute. Vấn đề là tôi không có đối tượng Throwable trong onPostExecute. Làm thế nào để bắt Ngoại lệ trong chủ đề không phải UI và in thông báo lỗi trong UI-thread?Bắt ngoại lệ của AsyncTask. Cần suy nghĩ
public class TestTask extends AsyncTask<Void, Void, List<String>> {
@Override
protected List<String> doInBackground(final Void... params) {
try {
...
return listOfString;
} catch(SomeCustomException e) {
...
return null;
}
}
@Override
protected void onPostExecute(final List<String> result) {
if(result == null) {
// print the error of the Throwable "e".
// The problem is I don't have the Throwable object here! So I can't check the type of exception.
}
}
}
Cập nhật sau câu trả lời Arun của:
Đây là lớp AsyncTask wrapper của tôi. Nó có ý định xử lý Exception trong doInBackground nhưng tôi không thể tìm ra giải pháp tốt để làm điều đó.
public abstract class AbstractWorkerTask<Params, Progress, Result>
extends AsyncTask<Params, Progress, Result>
implements Workable {
protected OnPreExecuteListener onPreExecuteListener;
protected OnPostExecuteListener<Result> onPostExecuteListener;
protected ExceptionHappenedListener exceptionHappendedListener;
private boolean working;
@Override
protected void onPreExecute() {
if (onPreExecuteListener != null) {
onPreExecuteListener.onPreExecute();
}
working = true;
}
@Override
protected void onPostExecute(final Result result) {
working = false;
if(/* .........*/) {
exceptionHappendedListener.exceptionHappended(e);
}
if (onPostExecuteListener != null) {
onPostExecuteListener.onPostExecute(result);
}
}
@Override
public boolean isWorking() {
return working;
}
public void setOnPreExecuteListener(final OnPreExecuteListener onPreExecuteListener) {
this.onPreExecuteListener = onPreExecuteListener;
}
public void setOnPostExecuteListener(final OnPostExecuteListener<Result> onPostExecuteListener) {
this.onPostExecuteListener = onPostExecuteListener;
}
public void setExceptionHappendedListener(final ExceptionHappenedListener exceptionHappendedListener) {
this.exceptionHappendedListener = exceptionHappendedListener;
}
public interface OnPreExecuteListener {
void onPreExecute();
}
public interface OnPostExecuteListener<Result> {
void onPostExecute(final Result result);
}
public interface ExceptionHappenedListener {
void exceptionHappended(Exception e);
}
}
bạn có thể thực hiện một số loại callbacks để thiết lập và nhận được lỗi. –
Tôi đã thử nhưng tôi không thể trả lại cả Ngoại lệ và Danh sách trong doInBackground. Làm thế nào để làm nó? –
Emerald214
thử trả về 'e.toString()' thay vì 'null' từ' catch' của 'doInBackground()' ... – GAMA