views:

1007

answers:

2

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

+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
That's...that's smart. I will do this from now on.
Klondike
Brilliant! No need to monkey with Handlers anymore
DroidIn.net
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
@OneWorld: Yes, that should be fine.
CommonsWare
A: 

Thanks for the tip. Neat way of handling exceptions.

Jay
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
@Droidln.net due to his small reputation he cant leave comments or rate up...
OneWorld
@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