I have an AsyncTask to do SQLite database migration in the background (create or upgrade). Let's say somehow an IOException or SQLiteException is thrown inside doInBackground and it's pointless for the app to continue running because database state might be not in desired state. I'm kind of confused on what to do in this situation.
I'm thinking about letting the application crash as soon as possible and show dialog with error message, but I'm not really sure how to this inside doInBackground, because:
Anyone has an advice on how to gracefully handle this situation?
In summary, the three most common issues with AsyncTask are: Memory leaks. Cancellation of background work. Computational cost.
AsyncTask is used to perform time talking operations in android, but it's marked as deprecated from android 11.
AsyncTask must be subclassed to be used. The subclass will override at least one method ( doInBackground(Params...) ), and most often will override a second one ( onPostExecute(Result) .)
You can't show dialog in non-ui thread. You can pass activity reference to async task. To handle this situation you can try catch the exception in doInBackground and re-throw it in onPostExecute
e.g.
private class MyAsyncTaskTask extends AsyncTask<...> {
private Activity ownerActivity;
private Exception exceptionToBeThrown;
public MyAsyncTaskTask(Activity activity) {
// keep activity reference
this.ownerActivity = activity;
}
protected Long doInBackground(...) {
try {
...
} catch (Exception e) {
// save exception and re-thrown it then.
exceptionToBeThrown = e;
}
}
protected void onPostExecute(...) {
// Check if exception exists.
if (exceptionToBeThrown != null) {
ownerActivity.handleXXX();
throw exceptionToBeThrown;
}
}
}
If you async task is in Acvitiy class, then you can directly access it, e.g.,
public class MyActivity extends Activity {
...
AsyncTask<...> task = new AsyncTask<...>() {
public void onPostExecute(...) {
// Access activity directly
MyActivity.this.xxx()
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With