O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Android Programming: The Big Nerd Ranch Guide, 2nd Edition

Book Description

Android Programming: The Big Nerd Ranch Guide is an introductory Android book for programmers with Java experience.

Based on Big Nerd Ranch's popular Android Bootcamp course, this guide will lead you through the wilderness using hands-on example apps combined with clear explanations of key concepts and APIs. This book focuses on practical techniques for developing apps compatible with Android 4.1 (Jelly Bean) and up, including coverage of Lollipop and material design.

Write and run code every step of the way, creating apps that integrate with other Android apps, download and display pictures from the web, play sounds, and more. Each chapter and app has been designed and tested to provide the knowledge and experience you need to get started in Android development.

Big Nerd Ranch specializes in developing and designing innovative applications for clients around the world. Our experts teach others through our books, bootcamps, and onsite training. Whether it's Android, iOS, Ruby and Ruby on Rails, Cocoa, Mac OS X, JavaScript, HTML5 or UX/UI, we've got you covered.

The Android team is constantly improving and updating Android Studio and other tools. As a result, some of the instructions we provide in the book are no longer correct. You can find an addendum addressing breaking changes at:


Table of Contents

  1. Title Page
  2. Dedication
  3. Acknowledgments
  4. Table of Contents
  5. Learning Android
    1. Prerequisites
    2. What's New in the Second Edition?
    3. How to Use This Book
    4. How This Book is Organized
      1. Challenges
      2. Are you more curious?
    5. Code Style
    6. Typographical Conventions
    7. Using an eBook
    8. Android Versions
  6. The Necessary Tools
    1. Downloading and Installing Android Studio
    2. Downloading Earlier SDK Versions
    3. An Alternative Emulator
    4. A Hardware Device
  7. 1. Your First Android Application
    1. App Basics
    2. Creating an Android Project
    3. Navigating in Android Studio
    4. Laying Out the User Interface
      1. The view hierarchy
      2. Widget attributes
        1. android:layout_width and android:layout_height
        2. android:orientation
        3. android:text
      3. Creating string resources
      4. Previewing the layout
    5. From Layout XML to View Objects
      1. Resources and resource IDs
    6. Wiring Up Widgets
      1. Getting references to widgets
      2. Setting listeners
        1. Using anonymous inner classes
    7. Making Toasts
      1. Using code completion
    8. Running on the Emulator
    9. For the More Curious: Android Build Process
      1. Android build tools
  8. 2. Android and Model-View-Controller
    1. Creating a New Class
      1. Generating getters and setters
    2. Model-View-Controller and Android
      1. Benefits of MVC
    3. Updating the View Layer
    4. Updating the Controller Layer
    5. Running on a Device
      1. Connecting your device
      2. Configuring your device for development
    6. Adding an Icon
      1. Adding resources to a project
      2. Referencing resources in XML
    7. Challenges
    8. Challenge: Add a Listener to the TextView
    9. Challenge: Add a Previous Button
    10. Challenge: From Button to ImageButton
  9. 3. The Activity Lifecycle
    1. Logging the Activity Lifecycle
      1. Making log messages
      2. Using LogCat
    2. Rotation and the Activity Lifecycle
      1. Device configurations and alternative resources
        1. Creating a landscape layout
    3. Saving Data Across Rotation
      1. Overriding onSaveInstanceState(Bundle)
    4. The Activity Lifecycle, Revisited
    5. For the More Curious: Testing onSaveInstanceState(Bundle)
    6. For the More Curious: Logging Levels and Methods
  10. 4. Debugging Android Apps
    1. Exceptions and Stack Traces
      1. Diagnosing misbehaviors
      2. Logging stack traces
      3. Setting breakpoints
      4. Using exception breakpoints
    2. Android-Specific Debugging
      1. Using Android Lint
      2. Issues with the R class
  11. 5. Your Second Activity
    1. Setting Up a Second Activity
      1. Creating a new activity
      2. A new activity subclass
      3. Declaring activities in the manifest
      4. Adding a Cheat! button to QuizActivity
    2. Starting an Activity
      1. Communicating with intents
        1. Explicit and implicit intents
    3. Passing Data Between Activities
      1. Using intent extras
      2. Getting a result back from a child activity
        1. Setting a result
        2. Sending back an intent
        3. Handling a result
    4. How Android Sees Your Activities
    5. Challenge
  12. 6. Android SDK Versions and Compatibility
    1. Android SDK Versions
    2. Compatibility and Android Programming
      1. A sane minimum
      2. Minimum SDK version
      3. Target SDK version
      4. Compile SDK version
      5. Adding code from later APIs safely
    3. Using the Android Developer Documentation
    4. Challenge: Reporting the Build Version
  13. 7. UI Fragments and the Fragment Manager
    1. The Need for UI Flexibility
    2. Introducing Fragments
    3. Starting CriminalIntent
      1. Creating a new project
      2. Fragments and the support library
      3. Adding dependencies in Android Studio
      4. Creating the Crime class
    4. Hosting a UI Fragment
      1. The fragment lifecycle
      2. Two approaches to hosting
      3. Defining a container view
    5. Creating a UI Fragment
      1. Defining CrimeFragment’s layout
      2. Creating the CrimeFragment class
        1. Implementing fragment lifecycle methods
        2. Wiring widgets in a fragment
    6. Adding a UI Fragment to the FragmentManager
      1. Fragment transactions
      2. The FragmentManager and the fragment lifecycle
    7. Application Architecture with Fragments
      1. The reason all our activities will use fragments
    8. For the More Curious: Why Support Fragments are Superior
    9. For the More Curious: Using Built-In Fragments
  14. 8. Creating User Interfaces with Layouts and Widgets
    1. Upgrading Crime
    2. Updating the Layout
    3. Wiring Widgets
    4. More on XML Layout Attributes
      1. Styles, themes, and theme attributes
      2. Screen pixel densities and dp and sp
      3. Android’s design guidelines
      4. Layout parameters
      5. Margins vs. padding
    5. Using the Graphical Layout Tool
      1. Creating a landscape layout
      2. Adding a new widget
      3. Editing attributes in properties view
      4. Reorganizing widgets in the component tree
      5. Updating child layout parameters
      6. How android:layout_weight works
      7. The graphical layout tool and you
      8. Widget IDs and multiple layouts
    6. Challenge: Formatting the Date
  15. 9. Displaying Lists with RecyclerView
    1. Updating CriminalIntent’s Model Layer
      1. Singletons and centralized data storage
    2. An Abstract Activity for Hosting a Fragment
      1. A generic fragment-hosting layout
      2. An abstract Activity class
        1. Using an abstract class
        2. Creating the new controllers
        3. Declaring CrimeListActivity
    3. RecyclerView, Adapter, and ViewHolder
      1. ViewHolders and Adapters
        1. Adapters
      2. Using a RecyclerView
      3. Implementing an Adapter and ViewHolder
    4. Customizing List Items
      1. Creating the list item layout
      2. Using a custom item view
    5. Responding to Presses
    6. For the More Curious: ListView and GridView
    7. For the More Curious: Singletons
  16. 10. Using Fragment Arguments
    1. Starting an Activity from a Fragment
      1. Putting an extra
      2. Retrieving an extra
      3. Updating CrimeFragment’s view with Crime data
      4. The downside to direct retrieval
    2. Fragment Arguments
      1. Attaching arguments to a fragment
      2. Retrieving arguments
    3. Reloading the List
    4. Getting Results with Fragments
    5. Challenge: Efficient RecyclerView Reloading
    6. For the More Curious: Why Use Fragment Arguments?
  17. 11. Using ViewPager
    1. Creating CrimePagerActivity
      1. ViewPager and PagerAdapter
      2. Integrating CrimePagerActivity
    2. FragmentStatePagerAdapter vs. FragmentPagerAdapter
    3. For the More Curious: How ViewPager Really Works
    4. For the More Curious: Laying Out Views in Code
  18. 12. Dialogs
    1. The AppCompat Library
    2. Creating a DialogFragment
      1. Showing a DialogFragment
      2. Setting a dialog’s contents
    3. Passing Data Between Two Fragments
      1. Passing data to DatePickerFragment
      2. Returning data to CrimeFragment
        1. Setting a target fragment
        2. Sending data to the target fragment
        3. More flexibility in presenting a DialogFragment
    4. Challenge: More Dialogs
    5. Challenge: A Responsive DialogFragment
  19. 13. The Toolbar
    1. AppCompat
      1. Using the AppCompat library
        1. Updating the theme
        2. Using AppCompatActivity
    2. Menus
      1. Defining a menu in XML
        1. The app namespace
        2. Using Android Asset Studio
      2. Creating the menu
      3. Responding to menu selections
    3. Enabling Hierarchical Navigation
      1. How hierarchical navigation works
    4. An Alternative Action Item
      1. Toggling the action item title
      2. “Just one more thing...”
    5. For the More Curious: Toolbar vs Action Bar
    6. Challenge: Deleting Crimes
    7. Challenge: Plural String Resources
    8. Challenge: An Empty View for the RecyclerView
  20. 14. SQLite Databases
    1. Defining a Schema
    2. Building Your Initial Database
      1. Debugging database issues
    3. Gutting CrimeLab
    4. Writing to the Database
      1. Using ContentValues
      2. Inserting and updating rows
    5. Reading from the Database
      1. Using a CursorWrapper
      2. Converting to model objects
        1. Refreshing model data
    6. For the More Curious: More Databases
    7. For the More Curious: The Application Context
    8. Challenge: Deleting Crimes
  21. 15. Implicit Intents
    1. Adding Buttons
    2. Adding a Suspect to the Model Layer
    3. Using a Format String
    4. Using Implicit Intents
      1. Parts of an implicit intent
      2. Sending a crime report
      3. Asking Android for a contact
        1. Getting the data from the contact list
        2. Contacts permissions
      4. Checking for responding activities
    5. Challenge: ShareCompat
    6. Challenge: Another Implicit Intent
  22. 16. Taking Pictures with Intents
    1. A Place for Your Photo
      1. Including layout files
    2. External Storage
      1. Designating a picture location
    3. Using a Camera Intent
      1. External storage permission
      2. Firing the intent
    4. Scaling and Displaying Bitmaps
    5. Declaring Features
    6. For the More Curious: Using Includes
    7. Challenge: Detail Display
    8. Challenge: Efficient Thumbnail Load
  23. 17. Two-Pane Master-Detail Interfaces
    1. Adding Layout Flexibility
      1. Modifying SingleFragmentActivity
      2. Creating a layout with two fragment containers
      3. Using an alias resource
      4. Creating tablet alternatives
    2. Activity: Fragment Boss
      1. Fragment callback interfaces
        1. Implementing CrimeListFragment.Callbacks
        2. Implementing CrimeFragment.Callbacks
    3. For the More Curious: More on Determining Device Size
  24. 18. Assets
    1. Why Assets, Not Resources
    2. Creating BeatBox
    3. Importing Assets
    4. Getting at Assets
    5. Wiring Up Assets for Use
    6. Accessing Assets
    7. For the More Curious: Non-Assets?
  25. 19. Audio Playback with SoundPool
    1. Creating a SoundPool
    2. Loading Sounds
    3. Playing Sounds
    4. Unloading Sounds
    5. Rotation and Object Continuity
      1. Retaining a fragment
      2. Rotation and retained fragments
    6. For the More Curious: Whether to Retain
    7. For the More Curious: More on Rotation Handling
  26. 20. Styles and Themes
    1. Color Resources
    2. Styles
      1. Style inheritance
    3. Themes
      1. Modifying the theme
    4. Adding Theme Colors
    5. Overriding Theme Attributes
      1. Theme spelunking
    6. Modifying Button Attributes
    7. For the More Curious: More on Style Inheritance
    8. For the More Curious: Accessing Theme Attributes
    9. Challenge: An Appropriate Base Theme
  27. 21. XML Drawables
    1. Making Uniform Buttons
    2. Shape Drawables
    3. State List Drawables
    4. Layer List Drawables
    5. For the More Curious: Why Bother with XML Drawables?
    6. For the More Curious: 9-Patch Images
    7. For the More Curious: Mipmap Images
  28. 22. More About Intents and Tasks
    1. Setting Up NerdLauncher
    2. Resolving an Implicit Intent
    3. Creating Explicit Intents at Runtime
    4. Tasks and the Back Stack
      1. Switching between tasks
      2. Starting a new task
    5. Using NerdLauncher as a Home Screen
    6. Challenge: Icons
    7. For the More Curious: Processes vs. Tasks
    8. For the More Curious: Concurrent Documents
  29. 23. HTTP & Background Tasks
    1. Creating PhotoGallery
    2. Networking Basics
      1. Asking permission to network
    3. Using AsyncTask to Run on a Background Thread
    4. You and Your Main Thread
      1. Beyond the main thread
    5. Fetching JSON from Flickr
      1. Parsing JSON text
    6. From AsyncTask Back to the Main Thread
    7. Cleaning Up AsyncTasks
    8. For the More Curious: More on AsyncTask
    9. For the More Curious: Alternatives to AsyncTask
    10. Challenge: Gson
    11. Challenge: Paging
    12. Challenge: Dynamically Adjusting the Number of Columns
  30. 24. Loopers, Handlers, and HandlerThread
    1. Preparing RecyclerView to Display Images
    2. Downloading Lots of Small Things
    3. Communicating with the Main Thread
    4. Assembling a Background Thread
    5. Messages and Message Handlers
      1. Message anatomy
      2. Handler anatomy
      3. Using handlers
      4. Passing handlers
    6. For the More Curious: AsyncTask vs. Threads
    7. Challenge: Preloading and Caching
    8. For the More Curious: Solving the Image Downloading Problem
  31. 25. Search
    1. Searching Flickr
    2. Using SearchView
      1. Responding to SearchView user interactions
    3. Simple Persistence with Shared Preferences
    4. Polishing Your App
    5. Challenge: Polishing Your App Some More
  32. 26. Background Services
    1. Creating an IntentService
    2. What Services are For
      1. Safe background networking
    3. Looking for New Results
    4. Delayed Execution with AlarmManager
      1. Being a good citizen: using alarms the right way
        1. Inexact vs. exact repeating
        2. Time basis options
      2. PendingIntent
      3. Managing alarms with PendingIntent
    5. Controlling Your Alarm
    6. Notifications
    7. Challenge: Notifications on Android Wear
    8. For the More Curious: Service Details
      1. What a service does (and does not) do
      2. A service’s lifecycle
      3. Non-sticky services
      4. Sticky services
      5. Bound services
        1. Local service binding
        2. Remote service binding
    9. For the More Curious: JobScheduler and JobServices
    10. For the More Curious: Sync Adapters
    11. Challenge: Using JobService on Lollipop
  33. 27. Broadcast Intents
    1. Regular Intents vs. Broadcast Intents
    2. Receiving a System Broadcast: Waking Up on Boot
      1. Creating and registering a standalone receiver
      2. Using receivers
    3. Filtering Foreground Notifications
      1. Sending broadcast intents
      2. Creating and registering a dynamic receiver
      3. Limiting broadcasts to your app using private permissions
        1. More about protection levels
      4. Passing and receiving data with ordered broadcasts
    4. Receivers and Long-Running Tasks
    5. For the More Curious: Local Events
      1. Using EventBus
      2. Using RxJava
    6. For the More Curious: Detecting the Visibility of Your Fragment
  34. 28. Browsing the Web and WebView
    1. One Last Bit of Flickr Data
    2. The Easy Way: Implicit Intents
    3. The Harder Way: WebView
      1. Using WebChromeClient to spruce things up
    4. Proper Rotation with WebView
      1. Dangers of handling configuration changes
    5. For the More Curious: Injecting JavaScript Objects
    6. For the More Curious: KitKat’s WebView Overhaul
    7. Challenge: Using the Back Button for Browser History
    8. Challenge: Supporting Non-HTTP Links
  35. 29. Custom Views and Touch Events
    1. Setting Up the DragAndDraw Project
      1. Setting up DragAndDrawActivity
      2. Setting up DragAndDrawFragment
    2. Creating a Custom View
      1. Creating BoxDrawingView
    3. Handling Touch Events
      1. Tracking across motion events
    4. Rendering Inside onDraw(…)
    5. Challenge: Saving State
    6. Challenge: Rotating Boxes
  36. 30. Property Animation
    1. Building the Scene
    2. Simple Property Animation
      1. View transformation properties
      2. Using different interpolators
      3. Color evaluation
    3. Playing Animators Together
    4. For the More Curious: Other Animation APIs
      1. Legacy animation tools
      2. Transitions
    5. Challenges
  37. 31. Locations and Play Services
    1. Locations and Libraries
      1. Google Play Services
    2. Creating Locatr
    3. Play Services and Location Testing on Emulators
      1. Mock location data
    4. Building out Locatr
    5. Setting Up Google Play Services
      1. Location permissions
    6. Using Google Play Services
    7. Flickr Geosearch
    8. Getting a Location Fix
    9. Find and Display an Image
    10. Challenge: Progress
  38. 32. Maps
    1. Importing Play Services Maps
    2. Mapping on Android
    3. Maps API Setup
      1. Getting a Maps API Key
        1. Your signing key
        2. Getting an API key
    4. Setting Up Your Map
    5. Getting More Location Data
    6. Working with Your Map
      1. Drawing on the map
    7. For the More Curious: Teams and API Keys
  39. 33. Material Design
    1. Material Surfaces
      1. Elevation and Z values
      2. State list animators
    2. Animation Tools
      1. Circular reveal
      2. Shared element transitions
    3. View Components
      1. Cards
      2. Floating action buttons
      3. Snackbars
    4. More on Material Design
  40. 34. Afterword
    1. The Final Challenge
    2. Shameless Plugs
    3. Thank You
  41. Index