NullPointerException


#1

When I tested out the final code (from the book, not the solutions) in this chapter, everything seemed to be working fine but after paging down and up for a bit, I got a NullPointerException.

11-25 06:22:45.267: E/AndroidRuntime(2203): FATAL EXCEPTION: ThumbnailDownloader
11-25 06:22:45.267: E/AndroidRuntime(2203): java.lang.NullPointerException
11-25 06:22:45.267: E/AndroidRuntime(2203): at com.bignerdranch.android.photogallery.ThumbnailDownloader.handleRequest(ThumbnailDownloader.java:81)
11-25 06:22:45.267: E/AndroidRuntime(2203): at com.bignerdranch.android.photogallery.ThumbnailDownloader.access$0(ThumbnailDownloader.java:72)
11-25 06:22:45.267: E/AndroidRuntime(2203): at com.bignerdranch.android.photogallery.ThumbnailDownloader$1.handleMessage(ThumbnailDownloader.java:57)
11-25 06:22:45.267: E/AndroidRuntime(2203): at android.os.Handler.dispatchMessage(Handler.java:99)
11-25 06:22:45.267: E/AndroidRuntime(2203): at android.os.Looper.loop(Looper.java:137)
11-25 06:22:45.267: E/AndroidRuntime(2203): at android.os.HandlerThread.run(HandlerThread.java:61)


#2

The problem is FlickrFetchr().getUrlBytes(url) sometimes returns null. If you check for that, it works.


#3

Confirmed!

FlickrFetchr().getUrlBytes(url) returns null if connection.getResponseCode() != HttpURLConnection.HTTP_OK. Then the dereference to get the length from bitmapBytes causes the exception.

On page 444, you need to add the following between the lines that calls FlickrFetch().getUrlBytes(url) and the line that uses the BitmapFactory:

if (bitmapBytes == null) return;

Interestingly, I didn’t find this error until I was adding services in chapter 29. I attached the debugger to look at the log and kept running into that GaiException everyone else kept hitting because I left the RuntimeException breakpoint enabled. Perhaps the debugger halting execution had something to do with the connection returning not ok, and thus the null pointer exception showing up.


#4

The reason for this error is likely that the small image URL was not available in the XML (image metadata) that you downloaded in the AsyncTask. Then you try to fetch a null URL, and clearly get a non HTTP_OK result in doing so.

I added two checks. The safety check, which was mentioned above, is added after your call to getUrlBytes() so that you don’t make a call on a null byte[] array. The extra check you should add, is to not even bother enqueuing a null or empty string URL for download in the first place.