Table Of ContentAndroid Programming: The Big Nerd Ranch Guide
by Bill Phillips, Chris Stewart and Kristin Marsicano
Copyright © 2017 Big Nerd Ranch, LLC.
All rights reserved. Printed in the United States of America. This publication is protected by copyright, and
permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system,
or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For
information regarding permissions, contact
Big Nerd Ranch, LLC.
200 Arizona Ave NE
Atlanta, GA 30307
(770) 817-6373
http://www.bignerdranch.com/
book-comments@bignerdranch.com
The 10-gallon hat with propeller logo is a trademark of Big Nerd Ranch, Inc.
Exclusive worldwide distribution of the English edition of this book by
Pearson Technology Group
800 East 96th Street
Indianapolis, IN 46240 USA
http://www.informit.com
The authors and publisher have taken care in writing and printing this book but make no expressed or implied
warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental
or consequential damages in connection with or arising out of the use of the information or programs contained
herein.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the
designations have been printed with initial capital letters or in all capitals.
ISBN-10 0134706099
ISBN-13 978-0134706092
Third edition, first printing, February 2017
Release D.3.1.1
Dedication
To the record player on my desk. Thanks for keeping me company
through all this. I promise I’ll get you a new needle soon.
— B.P.
To my dad, David, for teaching me the value of hard work. To my mom,
Lisa, for pushing me to always do the right thing.
— C.S.
To my dad, Dave Vadas, for inspiring and encouraging me to pursue a
career in computing. And to my mom, Joan Vadas, for cheering me on
through all the ups and downs (and for reminding me that watching an
episode of The Golden Girls always makes things better).
— K.M.
iii
Acknowledgments
With this being our third edition, we find ourselves used to saying this. It always needs to be said,
though: Books are not created by authors alone. They are shepherded into existence by a community
of collaborators, risk-takers, and other supporters, without whom the burden of comprehending and
writing all this material would be crippling.
• Brian Hardy, who, along with Bill, had the gusto to bring the very first edition of this book into
the world. From nothing, Brian and Bill made something great.
• Our co-instructors and members of our Android development team: Andrew Lunsford, Bolot
Kerimbaev, Brian Gardner, David Greenhalgh, Josh Skeen, Matt Compton, Paul Turner, and
Rashad Cureton. (Soon, Rashad. Soon.) They taught everything in this book before it was
polished enough to be presentable and gave us many invaluable suggestions and corrections. Most
people live their entire lives without ever working with such a talented and entertaining crew.
They make work at Big Nerd Ranch an everyday joy.
• Special thanks to Andrew, who went through the entire book and updated all the Android Studio
screenshots. We appreciate his thoroughness, attention to detail, and acerbic wit.
• Zack Simon, our fantastically talented and soft-spoken Big Nerd Ranch designer. Unbeknownst
to us, Zack went behind our backs and updated the nifty cheat sheet you can find attached to this
book. If you enjoy that sheet, you should find Zack and tell him so yourself. But we will also
thank Zack right here: Thanks, Zack!
• Kar Loong Wong, for his work redesigning the crime list screen. The more help we get from Kar,
the better the apps in this book look. Thanks, Kar.
• Mark Dalrymple, who reviewed our constraint layout coverage for accuracy and wonderfulness. If
you happen to run into Mark, ask him to review your constraint layout coverage. He is so good at
doing that! But if you have none, ask him to make balloon animals for you instead.
• Thanks to Aaron Hillegass. As a practical matter, it is not possible to do this work without Big
Nerd Ranch, the company Aaron founded. Thank you.
• Our editor, Elizabeth Holaday. The famous beat author William S. Burroughs sometimes wrote by
cutting up his work into little pieces, throwing them in the air, and publishing the rearrangement.
Without a strong editor like Liz, our confusion and simpleminded excitement may have caused
us to resort to such techniques. We are thankful that she was there to impose focus, precision, and
clarity on our drafts.
• Ellie Volckhausen, who designed our cover.
• Anna Bentley, our copyeditor, and Simone Payment, our proofreader. Thank you both for sanding
away the remaining rough edges of this book.
• Chris Loper at IntelligentEnglish.com, who designed and produced the print and ebook versions
of the book. His DocBook toolchain made life much easier, too.
v
Acknowledgments
Finally, thanks to our students. There is a feedback loop between us and our students: We teach them
out of these materials, and they respond to it. Without that loop, this book could never have existed, nor
could it be maintained. If Big Nerd Ranch books are special (and we hope they are), it is that feedback
loop that makes them so. Thank you.
vi
Table of Contents
Learning Android ........................................................................................................... xix
Prerequisites .......................................................................................................... xix
What’s New in the Third Edition? ............................................................................. xix
How to Use This Book ............................................................................................. xx
How This Book Is Organized .................................................................................... xx
Challenges ..................................................................................................... xxi
Are you more curious? .................................................................................... xxi
Code Style ............................................................................................................. xxi
Typographical Conventions ...................................................................................... xxii
Android Versions ................................................................................................... xxii
The Necessary Tools ..................................................................................................... xxiii
Downloading and Installing Android Studio .............................................................. xxiii
Downloading Earlier SDK Versions ......................................................................... xxiii
A Hardware Device ............................................................................................... xxiv
1. Your First Android Application ........................................................................................ 1
App Basics ............................................................................................................... 2
Creating an Android Project ........................................................................................ 3
Navigating in Android Studio ...................................................................................... 8
Laying Out the UI ..................................................................................................... 9
The view hierarchy .......................................................................................... 13
Widget attributes ............................................................................................. 14
Creating string resources ................................................................................... 15
Previewing the layout ....................................................................................... 16
From Layout XML to View Objects ........................................................................... 17
Resources and resource IDs ............................................................................... 18
Wiring Up Widgets .................................................................................................. 21
Getting references to widgets ............................................................................. 22
Setting listeners ............................................................................................... 23
Making Toasts ......................................................................................................... 25
Using code completion ..................................................................................... 26
Running on the Emulator .......................................................................................... 27
For the More Curious: Android Build Process .............................................................. 30
Android build tools .......................................................................................... 31
Challenges .............................................................................................................. 32
Challenge: Customizing the Toast ............................................................................... 32
2. Android and Model-View-Controller ............................................................................... 33
Creating a New Class ............................................................................................... 34
Generating getters and setters ............................................................................ 35
Model-View-Controller and Android ........................................................................... 37
Benefits of MVC ............................................................................................. 38
Updating the View Layer .......................................................................................... 39
Updating the Controller Layer ................................................................................... 41
Running on a Device ............................................................................................... 46
Connecting your device .................................................................................... 46
Configuring your device for development ............................................................ 46
vii
Android Programming
Adding an Icon ....................................................................................................... 48
Adding resources to a project ............................................................................ 49
Referencing resources in XML .......................................................................... 51
Challenge: Add a Listener to the TextView .................................................................. 52
Challenge: Add a Previous Button .............................................................................. 52
Challenge: From Button to ImageButton ...................................................................... 53
3. The Activity Lifecycle .................................................................................................. 55
Logging the Activity Lifecycle .................................................................................. 57
Making log messages ....................................................................................... 57
Using Logcat .................................................................................................. 59
Exploring the activity lifecycle by example .......................................................... 60
Rotation and the Activity Lifecycle ............................................................................ 63
Device configurations and alternative resources ..................................................... 63
Saving Data Across Rotation ..................................................................................... 68
Overriding onSaveInstanceState(Bundle) .............................................................. 69
The Activity Lifecycle, Revisited ............................................................................... 70
For the More Curious: Current State of Activity Cleanup ................................................ 72
For the More Curious: Log Levels and Methods ........................................................... 73
Challenge: Preventing Repeat Answers ........................................................................ 74
Challenge: Graded Quiz ............................................................................................ 74
4. Debugging Android Apps .............................................................................................. 75
Exceptions and Stack Traces ..................................................................................... 76
Diagnosing misbehaviors .................................................................................. 78
Logging stack traces ........................................................................................ 78
Setting breakpoints .......................................................................................... 80
Using exception breakpoints .............................................................................. 83
Android-Specific Debugging ...................................................................................... 85
Using Android Lint .......................................................................................... 85
Issues with the R class ..................................................................................... 87
Challenge: Exploring the Layout Inspector ................................................................... 88
Challenge: Exploring Allocation Tracking .................................................................... 89
5. Your Second Activity ................................................................................................... 91
Setting Up a Second Activity .................................................................................... 93
Creating a new activity ..................................................................................... 93
A new activity subclass .................................................................................... 96
Declaring activities in the manifest ..................................................................... 97
Adding a cheat button to QuizActivity ................................................................ 98
Starting an Activity .................................................................................................. 99
Communicating with intents ............................................................................ 100
Passing Data Between Activities ............................................................................... 101
Using intent extras ......................................................................................... 102
Getting a result back from a child activity .......................................................... 105
How Android Sees Your Activities ............................................................................ 109
Challenge: Closing Loopholes for Cheaters ................................................................ 112
6. Android SDK Versions and Compatibility ....................................................................... 113
Android SDK Versions ........................................................................................... 113
Compatibility and Android Programming ................................................................... 114
A sane minimum ........................................................................................... 114
viii
Android Programming
Minimum SDK version ................................................................................... 117
Target SDK version ........................................................................................ 117
Compile SDK version ..................................................................................... 117
Adding code from later APIs safely .................................................................. 118
Using the Android Developer Documentation ............................................................. 120
Challenge: Reporting the Build Version ..................................................................... 122
Challenge: Limited Cheats ....................................................................................... 122
7. UI Fragments and the Fragment Manager ....................................................................... 123
The Need for UI Flexibility ..................................................................................... 124
Introducing Fragments ............................................................................................ 125
Starting CriminalIntent ............................................................................................ 126
Creating a new project .................................................................................... 129
Two types of fragments ................................................................................... 130
Adding dependencies in Android Studio ............................................................ 131
Creating the Crime class ................................................................................. 134
Hosting a UI Fragment ........................................................................................... 136
The fragment lifecycle .................................................................................... 136
Two approaches to hosting .............................................................................. 137
Defining a container view ............................................................................... 137
Creating a UI Fragment .......................................................................................... 139
Defining CrimeFragment’s layout ..................................................................... 139
Creating the CrimeFragment class ..................................................................... 142
Adding a UI Fragment to the FragmentManager .......................................................... 148
Fragment transactions ..................................................................................... 149
The FragmentManager and the fragment lifecycle ................................................ 152
Application Architecture with Fragments ................................................................... 153
The reason all our activities will use fragments ................................................... 154
For the More Curious: Fragments and the Support Library ............................................ 155
For the More Curious: Why Support Fragments Are Superior ........................................ 156
8. Displaying Lists with RecyclerView .............................................................................. 157
Updating CriminalIntent’s Model Layer ..................................................................... 159
Singletons and centralized data storage .............................................................. 159
An Abstract Activity for Hosting a Fragment .............................................................. 161
A generic fragment-hosting layout .................................................................... 161
An abstract Activity class ................................................................................ 162
RecyclerView, Adapter, and ViewHolder .................................................................... 167
ViewHolders and Adapters .............................................................................. 168
Using a RecyclerView .................................................................................... 171
A view to display .......................................................................................... 173
Implementing a ViewHolder and an Adapter ....................................................... 173
Binding List Items ................................................................................................. 176
Responding to Presses ............................................................................................ 178
For the More Curious: ListView and GridView ........................................................... 179
For the More Curious: Singletons ............................................................................. 179
Challenge: RecyclerView ViewTypes ......................................................................... 180
9. Creating User Interfaces with Layouts and Widgets .......................................................... 181
Using the Graphical Layout Tool .............................................................................. 182
Introducing ConstraintLayout ................................................................................... 183
ix
Android Programming
Using ConstraintLayout .................................................................................. 184
The graphical editor ....................................................................................... 186
Making room ................................................................................................ 188
Adding widgets ............................................................................................. 190
ConstraintLayout’s inner workings .................................................................... 194
Editing properties ........................................................................................... 195
Making list items dynamic .............................................................................. 199
More on Layout Attributes ...................................................................................... 200
Screen pixel densities and dp and sp ................................................................. 200
Margins vs padding ........................................................................................ 202
Styles, themes, and theme attributes .................................................................. 203
Android’s design guidelines ............................................................................. 204
The Graphical Layout Tools and You ........................................................................ 204
Challenge: Formatting the Date ................................................................................ 204
10. Using Fragment Arguments ........................................................................................ 205
Starting an Activity from a Fragment ........................................................................ 205
Putting an extra ............................................................................................. 207
Retrieving an extra ......................................................................................... 207
Updating CrimeFragment’s view with Crime data ................................................ 208
The downside to direct retrieval ........................................................................ 209
Fragment Arguments .............................................................................................. 210
Attaching arguments to a fragment .................................................................... 210
Retrieving arguments ...................................................................................... 211
Reloading the List .................................................................................................. 212
Getting Results with Fragments ................................................................................ 215
For the More Curious: Why Use Fragment Arguments? ................................................ 216
Challenge: Efficient RecyclerView Reloading ............................................................. 216
Challenge: Improving CrimeLab Performance ............................................................. 216
11. Using ViewPager ...................................................................................................... 217
Creating CrimePagerActivity .................................................................................... 219
ViewPager and PagerAdapter ........................................................................... 219
Integrating CrimePagerActivity ......................................................................... 221
FragmentStatePagerAdapter vs FragmentPagerAdapter ................................................. 223
For the More Curious: How ViewPager Really Works .................................................. 224
For the More Curious: Laying Out Views in Code ....................................................... 225
Challenge: Restoring CrimeFragment’s Margins .......................................................... 226
Challenge: Adding First and Last Buttons .................................................................. 226
12. Dialogs ................................................................................................................... 227
Creating a DialogFragment ...................................................................................... 228
Showing a DialogFragment .............................................................................. 231
Setting a dialog’s contents ............................................................................... 232
Passing Data Between Two Fragments ....................................................................... 235
Passing data to DatePickerFragment .................................................................. 236
Returning data to CrimeFragment ..................................................................... 238
Challenge: More Dialogs ......................................................................................... 245
Challenge: A Responsive DialogFragment .................................................................. 245
13. The Toolbar ............................................................................................................. 247
AppCompat ........................................................................................................... 248
x