Listening to the View Lifecycle

Before running PhotoGallery and seeing your hard-won images, there is one last danger you need to account for. If the user rotates the screen, ThumbnailDownloader may be hanging on to invalid PhotoHolders. Your app could crash if ThumbnailDownloader tries to send a bitmap to a PhotoHolder that was part of a view that was destroyed across rotation.

Fix this leak by clearing all the requests out of your queue when the fragment’s view is destroyed. To do this, ThumbnailDownloader needs to know about the fragment’s view lifecycle. (Recall that the lifecycles for the fragment and its view diverge, since you are retaining the fragment: The view will be destroyed across rotation, but the fragment instance itself ...

Get Android Programming: The Big Nerd Ranch Guide, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.