Standard Defensive Coding in Handling an Activity Result


On page 108 we have the section for Handling a result and I have noticed that it is coded a little defensively and I am wondering if this is the normal standard.

So when I had a go before looking at the example code I didn’t check that the Intent object wasn’t null. I then realised that as the child Activity didn’t necessarily call setResult then the Intent object might not be passed back, so that was kind of valid. But then I just coded QuizActivity.onActivityResult to check that the resultCode was not RESULT_CANCELED before attempting the call to wasAnswerShown…

This has then led me to think if calling setResult should be standard for the child activity. So if it’s not called from the Cheatbutton handler then perhaps from onPause() method using a private variable to set the result data in the intent? So then there is always an Intent passed back to any activity that has created it with startActivityForResult.

Whilst all these methods work I am wondering what the general coding standard is, if there even is one for developing activity navigation.

btw, loving the book, might just be the best programming guide book I’ve ever read!

Thanks! I’m glad you’re enjoying the book.

It is common to be defensive in onActivityResult. Android provides no guarantees that the 2nd activity will set a result to send back to the first. Always check the result code and do not assume that the data intent exists (it could be null).

Even if the 2nd activity is one that you wrote, It is a common practice for the 2nd activity to not return a result on certain error cases.