I'm converting my code from using Handler
to AsyncTask
. The latter is great at what is does - async updates and handling of results in the main UI thread. What's unclear to me is how to handle exceptions if something goes haywire in AsyncTask#doInBackground
? The way I do it is to leave error Handler and send message to it. It works fine but is it the "right" approach and is there better alternative? Also I understand that if I define the error Handler as Activity field it should execute in UI thread, however, sometimes (very unpredictable) I will get Exception saying that my code (which is triggered from Handler#handleMessage
is executed in the wrong thread. Should I initialize error Handler in Activity#onCreate
instead? Placing runOnUiThread
into Handler#handleMessage seems redundant but that executes very reliably
views:
1007answers:
2
+5
A:
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.
CommonsWare
2009-11-16 02:05:05
That's...that's smart. I will do this from now on.
Klondike
2009-11-16 04:33:18
Brilliant! No need to monkey with Handlers anymore
DroidIn.net
2009-11-16 05:47:19
Is this the way I should hold onto the Throwable or Exception? "Add an instance-variable to your own AsyncTask subclass that will hold the result of your background processing." When you get an exception, store the exception (or some other error-string/code) in this variable. When onPostExecute is called, see if this instance-variable is set to some error. If so, show an error message." (From the user "Streets of Boston" http://groups.google.com/group/android-developers/browse_thread/thread/ffa3d9c589f8d753)
OneWorld
2010-10-12 15:06:35
@OneWorld: Yes, that should be fine.
CommonsWare
2010-10-12 15:20:50
Jay - this is comment not an answer. I understand that you are new to this but people here take it seriously. If you don't want people to give you negative response I suggest you delete this and leave the comment instead
DroidIn.net
2010-10-12 04:03:34
@Droidln.net due to his small reputation he cant leave comments or rate up...
OneWorld
2010-10-12 14:58:32
@OneWorld, thanks for understanding. <br/>@DroidIn.net, I just wanted to express my thanks to this nice tip. It really encourages ppl to help each other. Once I've enough reputation point, I'll follow your suggestion.
Jay
2010-10-13 11:22:25