AsyncTask and error handling on Android
It works fine but is it the "right"
approach and is there better
alternative?
I hold onto the Throwable
or Exception
in the AsyncTask
instance itself and then do something with it in onPostExecute()
, so my error handling has the option of displaying a dialog on-screen.
How to gracefully handle exception inside AsyncTask in Android?
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()
}
}
}
How to set proper error message on AsyncTask in android studio?
You should create new AsyncTaskResult with passing your exception object, something like this :
AsyncTask<String, String, AsyncTaskResult<JSONObject>> jsonLoader = new AsyncTask<String, String, AsyncTaskResult<JSONObject>>() {
@Override
protected AsyncTaskResult<JSONObject> doInBackground(
String... params) {
try {
// get your JSONObject from the server
return new AsyncTaskResult<JSONObject>(JSon Object);
} catch (Exception E) {
return new AsyncTaskResult<JSONObject>(E);
}
}
protected void onPostExecute(AsyncTaskResult<JSONObject> result) {
if ( result.getError() != null ) {
// error handling here
} else {
JSONObject yourResult = result.getResult();
// result handling here
}
};
}
Async Task Error Handling
What you can do (I'm using this trick in my app) is this:
protected Object doInBackground(Object... arg0) {
try {
prs.setStation(strStation);
return null;
}
catch(Exception ex)
{
return ex;
}
}
protected void onPostExecute(Object result) {
progDialog.hide();
if(result != null && result instanceof Exception) {
String errText = ((Exception)result).getMessage();
//now deal with your exception on the UI thread
}
}
Managing exception in AsyncTask
I got the solution. Maybe, it is not the best one.
I get the lastBackup
outside AsyncTask, this way I can declare throws BackupException
.
public void remote(final Backup backup) throws BackupException {
local(backup);
final File lastBackup = getLastBackup();
AsyncTask.execute(new Runnable() {
@Override
public void run() {
BackupSendInfo sendInfo = new BackupSendInfo()
.setFile(lastBackup)
.setFileName(getBackupName(backup))
.setBackup(backup)
.setDeviceId("Desconocido") //TODO leer dispositivo del fichero deviceName
.setApp(config.getAppName());
fileSender.send(sendInfo);
}
});
}
Related Topics
Configuration with Name 'Default' Not Found. Android Studio
Install_Failed_Shared_User_Incompatible While Using Shared User Id
How to Create a .CSV on Android
Sharing a Png Image in Drawable Folder
How to Implement a Setonitemclicklistener Firebaserecyclerviewadapter
Android Device Gps On/Off Programmatically
Upload Video to Facebook in Android
How to Serialize My User Class for the Firebase Database and Fix This Error
How to Record Microphone to More Compressed Format During Webrtc Call on Android
Simple Mediaplayer Play Mp3 from File Path
Android Eclipse Noclassdeffounderror for External .Jar Files
Videoview Getdrawingcache Is Returning Black
Differencebetween @Id and @+Id
Android: Asynctask to Make an Http Get Request
How to Display Map in Android with Marker
Hw Accelerated Activity - How to Get Opengl Texture Size Limit
Webview Showing Err_Cleartext_Not_Permitted Although Site Is Https