You are previewing Android Programming: The Big Nerd Ranch Guide.
O'Reilly logo
Android Programming: The Big Nerd Ranch Guide

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 all versions of Android widely used today (Android 2.2 - 4.2). Write and run code every step of the way – creating apps that catalog crime scenes, browse photos, track your jogging route, 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.

Write and run code every step of the way — creating apps that catalog crime scenes, browse photos, track your jogging route, 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 provided the training we needed to get hundreds of engineers building skillfully on Android. This book is a great distillation of that training and will be a huge help to anyone looking to ramp up as well." – Mike Shaver, Director of Mobile Engineering, Facebook

"…a must-have for the developer just starting in Android or ready for more advanced techniques. I was impressed with this book’s content and clarity of presentation. The authors explain simple and complex Android topics with equal ease." – James Steele, author of The Android Developer's Cookbook

Table of Contents

  1. Title Page
  2. Dedication
  3. Acknowledgments
  4. Learning Android
    1. Prerequisites
    2. How to Use This Book
    3. How This Book Is Organized
      1. Challenges
      2. Are you more curious?
    4. Code Style
    5. Typographical Conventions
    6. Using an eBook
    7. The Necessary Tools
      1. The ADT Bundle
        1. Downloading and installing the bundle
        2. Downloading earlier SDK versions
        3. A hardware device
  5. 1. Your First Android Application
    1. App Basics
    2. Creating an Android Project
    3. Navigating in Eclipse
    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. Organizing imports
      2. Getting references to widgets
      3. Setting listeners
        1. Using anonymous inner classes
        2. Making toasts
        3. Using auto-complete
    7. Running on the Emulator
    8. For the More Curious: Android Build Process
      1. Android build tools
  6. 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
  7. 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
  8. 4. Debugging Android Apps
    1. The DDMS Perspective
    2. Exceptions and Stack Traces
      1. Diagnosing misbehaviors
      2. Logging stack traces
      3. Setting breakpoints
      4. Using exception breakpoints
    3. File Explorer
    4. Android-Specific Debugging
      1. Using Android Lint
      2. Issues with the R class
  9. 5. Your Second Activity
    1. Setting Up a Second Activity
      1. Creating a new layout
      2. Creating 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
          1. Sending back an intent
        2. Handling a result
    4. How Android Sees Your Activities
    5. Challenge
  10. 6. Android SDK Versions and Compatibility
    1. Android SDK Versions
    2. Compatibility and Android Programming
      1. Honeycomb was big
      2. Minimum SDK version
      3. Target SDK version
      4. Build SDK version
      5. Adding code from later APIs safely
        1. Suppressing Lint compatibility errors
    3. Using the Android Developer Documentation
    4. Challenge: Reporting the Build Version
  11. 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. 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. The Reason All Our Activities Will Use Fragments
    8. For the More Curious: Developing for Honeycomb, ICS, Jelly Bean, and Beyond
  12. 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. Adding a new widget
      2. Editing attributes in properties
      3. Reorganizing widgets in the outline view
      4. Updating child layout parameters
      5. How android:layout_weight works
      6. Summary of graphical layout tool
      7. Widget IDs and multiple layouts
    6. Challenge: Formatting the Date
  13. 9. Displaying Lists with ListFragment
    1. Updating CriminalIntent’s Model Layer
      1. Singletons and centralized data storage
    2. Creating a ListFragment
    3. An Abstract Activity for Hosting a Fragment
      1. A generic fragment-hosting layout
      2. An abstract Activity class
        1. Using an abstract class
        2. Declaring CrimeListActivity
    4. ListFragment, ListView, and ArrayAdapter
      1. Creating an ArrayAdapter<T>
      2. Responding to list item clicks
    5. Customizing List Items
      1. Creating the list item layout
      2. Creating an adapter subclass
  14. 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
  15. 11. Using ViewPager
    1. Creating CrimePagerActivity
      1. Laying out views in code
        1. Standalone ID resources
      2. ViewPager and PagerAdapter
      3. Integrating CrimePagerActivity
      4. FragmentStatePagerAdapter vs. FragmentPagerAdapter
    2. For the More Curious: How ViewPager Really Works
  16. 12. Dialogs
    1. Creating a DialogFragment
      1. Showing a DialogFragment
      2. Setting a dialog’s contents
    2. 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
    3. Challenge: More Dialogs
  17. 13. Audio Playback Using MediaPlayer
    1. Adding Resources
    2. Defining the layout for HelloMoonFragment
      1. Manually resetting the app theme
    3. Creating HelloMoonFragment
    4. Using a Layout Fragment
    5. Audio Playback
      1. Wiring buttons to play and stop
    6. Challenge: Pausing Audio Playback
    7. For the More Curious: Playing Video
    8. Challenge: Playing Video in HelloMoon
  18. 14. Retained Fragments
    1. Retaining a Fragment
    2. Rotation and Retained Fragments
    3. Retained Fragments: As Nice as All That?
    4. Rotation Handling and onSaveInstanceState(Bundle)
    5. For the More Curious: Rotation Before Fragments
  19. 15. Localization
    1. Localizing Resources
      1. Default resources
        1. Screen density works differently
    2. Configuration Qualifiers
      1. Prioritizing alternative resources
      2. Multiple qualifiers
      3. Finding the best-matching resources
        1. Ruling out incompatible directories
        2. Stepping through the precedence table
    3. More Resource Rules and Regulations
      1. Resource naming
      2. Resource directory structure
    4. Testing Alternative Resources
  20. 16. The Action Bar
    1. Options Menus
      1. Defining an options menu in XML
        1. Using system icons
      2. Creating the options menu
      3. Responding to options menu selections
    2. Enabling Ancestral Navigation
      1. Enabling the app icon
      2. Responding to the Up button
    3. An Alternative Menu Item
      1. Creating an alternative menu file
      2. Toggling the menu item title
      3. “Just one more thing...”
    4. Challenge: An Empty View for the List
  21. 17. Saving and Loading Local Files
    1. Saving and Loading Data in CriminalIntent
      1. Saving crime data to a JSON file
        1. Creating the CriminalIntentJSONSerializer class
        2. Making Crime class capable of JSON serialization
        3. Saving crimes in CrimeLab
        4. Saving application data in onPause()
      2. Loading crimes from the filesystem
    2. Challenge: Use External Storage
    3. For the More Curious: The Android Filesystem and Java I/O
      1. Accessing files and directories
  22. 18. Context Menus and Contextual Action Mode
    1. Defining a Context Menu Resource
    2. Implementing a Floating Context Menu
      1. Creating the context menu
      2. Registering for the context menu
      3. Responding to an action
    3. Implementing Contextual Action Mode
      1. Enabling multiple selection
      2. Action mode callbacks in a list view
      3. Changing activated item backgrounds
      4. Implementing contextual action mode in other views
    4. Compatibility: Fallback or Duplicate?
    5. Challenge: Deleting from CrimeFragment
    6. For the More Curious: ActionBarSherlock
    7. Challenge: Using ActionBarSherlock
      1. Basic ABS integration in CriminalIntent
      2. More advanced integration
      3. Even more advanced integration
  23. 19. Camera I: Viewfinder
    1. Creating the Fragment Layout
    2. Creating CrimeCameraFragment
    3. Creating CrimeCameraActivity
      1. Adding activity and camera permissions to the manifest
    4. Using the Camera API
      1. Opening and releasing the camera
      2. SurfaceView, SurfaceHolder, and Surface
      3. Determining preview size
      4. Starting CrimeCameraActivity from CrimeFragment
        1. Hiding the status bar and action bar
    5. For the More Curious: Running Activities from the Command Line
  24. 20. Camera II: Taking Pictures and Handling Images
    1. Taking a Picture
      1. Implementing Camera callbacks
      2. Setting the picture size
    2. Passing Data Back to CrimeFragment
      1. Starting CrimeCameraActivity for a result
      2. Setting a result in CrimeCameraFragment
      3. Retrieving filename in CrimeFragment
    3. Updating the Model Layer
      1. Adding a Photo class
      2. Giving Crime a photo property
      3. Setting the photo property
    4. Updating CrimeFragment’s View
      1. Adding an ImageView
      2. Image handling
        1. Adding scaled photo to the image view
        2. Unloading the image
    5. Showing Larger Image in a DialogFragment
    6. Challenge: Crime Image Orientation
    7. Challenge: Deleting Photos
    8. For the More Curious: Deprecation in Android
  25. 21. 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
          1. Contacts permissions
      4. Checking for responding activities
    5. Challenge: Another Implicit Intent
  26. 22. 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
        1. 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
  27. 23. 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
    5. Using NerdLauncher as a Home Screen
    6. Challenge: Icons, Reordering Tasks
    7. For the More Curious: Processes vs. Tasks
  28. 24. Styles And Includes
    1. Setting Up the RemoteControl Project
      1. Setting up RemoteControlActivity
      2. Setting up RemoteControlFragment
    2. Cleaning Up with Styles
    3. Finishing the Layout
    4. For the More Curious: include and merge
    5. Challenge: Style Inheritance
  29. 25. XML Drawables And 9-Patches
    1. XML Drawables
    2. State List Drawables
    3. Layer List and Inset Drawables
    4. Using 9-Patch Images
  30. 26. 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 XML From Flickr
      1. Using XmlPullParser
    6. From AsyncTask Back to the Main Thread
    7. For the More Curious: More on AsyncTask
      1. Cleaning Up AsyncTasks
    8. Challenge: Paging
  31. 27. Loopers, Handlers, and HandlerThread
    1. Preparing GridView for Displaying 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
  32. 28. Search
    1. Searching Flickr
    2. The Search Dialog
      1. Creating a search interface
      2. Searchable activities
      3. Hardware search button
      4. How Search works
      5. Launch modes and new intents
      6. Simple persistence with shared preferences
    3. Using SearchView on Post-Android 3.0
    4. Challenges
  33. 29. 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. PendingIntent
      2. Managing alarms with PendingIntent
    5. Controlling Your Alarm
      1. Updating options menu items
    6. Notifications
    7. For the More Curious: Service Details
      1. What 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
  34. 30. Broadcast Intents
    1. Waking Up on Boot
      1. Broadcast receivers in the manifest
      2. How to use receivers
    2. Filtering Foreground Notifications
      1. Sending broadcast intents
      2. Dynamic broadcast receivers
      3. Using private permissions
        1. More about protection levels
      4. Receiving results with ordered broadcasts
    3. Receivers and Long-running Tasks
  35. 31. Browsing The Web & 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
      2. Proper rotation with WebView
    4. For the More Curious: Injecting JavaScript Objects
  36. 32. 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: Rotations
  37. 33. Tracking the Device’s Location
    1. Getting Started with RunTracker
      1. Setting up RunActivity
      2. Setting up RunFragment
        1. Adding strings
        2. Obtaining the layout file
        3. Creating the RunFragment class
    2. Locations and the LocationManager
    3. Receiving Broadcast Location Updates
    4. Updating the UI with Location Data
    5. Faster Answers: the Last Known Location
    6. Testing Locations on Real and Virtual Devices
  38. 34. Local Databases with SQLite
    1. Storing Runs and Locations in a Database
    2. Querying a List of Runs From the Database
    3. Displaying a List of Runs Using CursorAdapter
    4. Creating New Runs
    5. Working with Existing Runs
    6. Challenge: Identifying the Current Run
  39. 35. Loading Asynchronous Data With Loaders
    1. Loaders and the LoaderManager
    2. Using Loaders in RunTracker
    3. Loading the List of Runs
    4. Loading a Single Run
    5. Loading the Last Location for a Run
  40. 36. Using Maps
    1. Adding the Maps API to RunTracker
      1. Use a real device to test maps
      2. Install and use the Google Play services SDK
      3. Obtain a Google Maps API key
      4. Update RunTracker’s manifest
    2. Showing the User’s Location on a Map
    3. Displaying a Run’s Path
    4. Adding Markers for Run Start and Finish
    5. Challenge: Live Updates
  41. 37. Afterword
    1. The Final Challenge
    2. Shameless Plugs
    3. Thank You
  42. Index
  43. More From Big Nerd Ranch...