Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 25  HTTP and Background Tasks


Challenge: Gson


Deserializing JSON in Java objects, as you did in Listing 25.12, is a common task in app development
regardless of the platform. Lots of smart people have created libraries to simplify the process of
converting JSON text to Java objects and back again.


One such library is Gson (github.com/google/gson). Gson maps JSON data to Java objects for you
automatically. This means you do not need to write any parsing code. For this reason, Gson is currently
our favorite JSON parsing library.


For this challenge, simplify your JSON parsing code in FlickrFetchr by incorporating the Gson
library into your app.


Challenge: Paging


By default, getRecent returns one page of 100 results. There is an additional parameter you can use
called page that will let you return page two, three, and so on.


For this challenge, implement a RecyclerView.OnScrollListener that detects when you are at the
end of your results and replaces the current page with the next page of results. For a slightly harder
challenge, append subsequent pages to your results.


Challenge: Dynamically Adjusting the Number of Columns


Currently the number of columns displayed in the grid is fixed at three. Update your code to provide a
dynamic number of columns so more columns appear in landscape and on larger devices.


A simple approach could involve providing an integer resource qualified for different orientations and/
or screen sizes. This is similar to the way you provided different layouts for different screen sizes in
Chapter 17. Integer resources should be placed in the res/values folder(s). Check out the Android
developer documentation for more details.


Providing qualified resources does not offer much in the way of granularity. For a more difficult
challenge (and a more flexible implementation), calculate and set the number of columns each time
the fragment’s view is created. Calculate the number of columns based on the current width of the
RecyclerView and some predetermined constant column width.


There is only one catch: You cannot calculate the number of columns in
onCreateView() because the RecyclerView will not be sized yet. Instead, implement a
ViewTreeObserver.OnGlobalLayoutListener and put your column calculation code in
onGlobalLayout(). Add the listener to your RecyclerView using addOnGlobalLayoutListener().

Free download pdf