NullPointer Bad Context in Adapter Init


I used this chapter’s model of custom array adapter and just got an interesting bug report from my app. The null pointer exception was thrown in the init of the custom array adapter similar to pg. 436 where the super routine is called for GalleryItemAdapter.

The problem is the use of getActivity() to pass in a context. Since this is being called in the context of the AsyncTask’s postExecute routine as a result of invoking setupAdapter() which activates the custom array adapter constructor, it is possible if the user has left the activity that this asynctask completes in the background.

I am thinking perhaps this would not happen if in onPause() or onDestroy() I actually canceled the AsyncTask?

How can I ensure that there is a valid context when code called by the postExecute method is invoked?