Log In
Or create an account ->
Imperial Library
Home
About
News
Upload
Forum
Help
Login/SignUp
Index
Head First: Android Development
Dedication
Authors of Head First Android Development
How to Use This Book: Intro
Who is this book for?
Who should probably back away from this book?
We know what you’re thinking
We know what your brain is thinking
Metacognition: thinking about thinking
Here’s what WE did:
Here’s what YOU can do to bend your brain into submission
Read me
The technical review team
Acknowledgments
Safari® Books Online
1. Getting Started: Diving In
Welcome to Androidville
Layouts define what each screen looks like
Java code defines what the app should do
Sometimes extra resources are needed too
The Android platform dissected
Here’s what we’re going to do
Your development environment
The Android SDK
Android Studio is a special version of IntelliJ IDEA
Install Java
Then install Android Studio
Build a basic app
Let’s build the basic app
1. Create a new project
2. Configure the project
3. Specify the API level
Activities and layouts from 50,000 feet
Building a basic app (continued)
4. Create an activity
Building a basic app (continued)
5. Configure the activity
You’ve just created your first Android app
Android Studio creates a complete folder structure for you
The folder structure includes different types of files
Useful files in your project
Edit code with the Android Studio editors
The code editor
The design editor
Run the app in the Android emulator
So what does the emulator look like?
Creating an Android Virtual Device
Open the Android Virtual Device Manager
Select the hardware
Select a system image
Verify the AVD configuration
Run the app in the emulator
Compile, package, deploy and run
You can watch progress in the console
Test drive
What just happened?
Refining the app
The app has one activity and one layout
The activity controls what the app does
The layout controls the app appearance
What’s in the layout?
The design editor
The code editor
activity_main.xml has two elements
The layout file contains a reference to a string, not the string itself
Let’s look in the strings.xml file
Update strings.xml to change the text
Take the app for a test drive
Your Android Toolbox
2. Building Interactive Apps: Apps That Do Something
You’re going to build a Beer Adviser app
Here’s what you need to do
Create the project
We’ve created a default activity and layout
Adding components with the design editor
Changes in the design editor are reflected in the XML
activity_find_beer.xml has a new button
Buttons and text views are subclasses of the same Android View class
android:id
android:text
android:layout_width, android:layout_height
A closer look at the layout code
The RelativeLayout element
The TextView element
The Button element
Changes to the XML...
...are reflected in the design editor
Use string resources rather than hardcoding the text
Change the layout to use the string resources
Let’s take the app for a test drive
Here’s what we’ve done so far
Add values to the spinner
Adding an array resource is similar to adding a string
Get the spinner to reference a string-array
Test drive the spinner
We need to make the button do something
Make the button call a method
Use onClick to say which method the button calls
What activity code looks like
Add an onClickFindBeer() method to the activity
onClickFindBeer() needs to do something
Use findViewById() to get a reference to a view
Once you have a View, you can access its methods
Setting the text in a TextView
Retrieving the selected value in a spinner
Update the activity code
The first version of the activity
What the code does
Test drive the changes
Building the custom Java class
Custom Java class spec
Build and test the Java class
Enhance the activity to call the custom Java class so that we can get REAL advice
Activity code version 2
What happens when you run the code
Test drive your app
Your Android Toolbox
3. Multiple Activities and Intents: State Your Intent
Apps can contain more than one activity
Here are the steps
Here’s the app structure
Create the project
Update the layout
Update strings.xml...
... and add the method to the activity
Create the second activity and layout
What just happened?
Welcome to the Android manifest file
Every activity needs to be declared
An intent is a type of message
Use an intent to start the second activity
What happens when you run the app
The story continues...
Test drive the app
Pass text to a second activity
Let’s start with the layout
Update the text view properties
putExtra() puts extra information in an intent
How to retrieve extra information from an intent
Update the CreateMessageActivity code
Get ReceiveMessageActivity to use the information in the intent
What happens when the user clicks the Send Message button
Test drive the app
We can change the app to send messages to other people
How Android apps work
Intents can start activities in other apps
But we don’t know what apps are on the device
Here’s what you’re going to do
Create an intent that specifies an action
How to create the intent
Adding extra information
Change the intent to use an action
What happens when the code runs
The story continues...
The intent filter tells Android which activities can handle which actions
How Android uses the intent filter
You need to run your app on a REAL device
1. Enable USB debugging on your device
2. Set up your system to detect your device
3. Plug your device into your computer with a USB cable
4. Run your app in Android Studio as normal
And here’s the app running on the physical device
Test drive the app
If you have one activity
If you have more than one activity
What if you ALWAYS want your users to choose an activity?
Intent.createChooser() displays a chooser dialog
What happens when you call createChooser()
The story continues...
Change the code to create a chooser
Update strings.xml...
... and update the onSendMessage() method
Test drive the app
If you have one activity
If you have more than one activity
If you have NO matching activities
Your Android Toolbox
4. The Activity Lifecycle: Being an Activity
How do activities really work?
The Stopwatch app
Build the app
The stopwatch layout code
The stopwatch strings.xml file
How the activity code will work
Add code for the buttons
The runTimer() method
Handlers allow you to schedule code
The post() method
The postDelayed() method
The full runTimer() code
The full StopwatchActivity code
What happens when you run the app
The story continues
Test drive the app
But there’s just one problem...
What just happened?
Rotating the screen changes the device configuration
From birth to death: the states of an activity
The activity lifecycle: from create to destroy
Your activity inherits the lifecycle methods
How do we deal with configuration changes?
Bypass re-creating the activity
Or save the current state...
...then restore the state in onCreate()
What happens when you run the app
The story continues
Test drive the app
There’s more to an activity’s life than create and destroy
Start, stop, and restart
The activity lifecycle: the visible lifetime
We need to implement two more lifecycle methods
Implement onStop() to stop the timer
The updated StopwatchActivity code
What happens when you run the app
Test drive the app
But what if an app is only partially visible?
The activity lifecycle: the foreground lifetime
Stop the stopwatch if the activity’s paused
What happens when you run the app
Test drive the app
The complete activity code
Your handy guide to the lifecycle methods
Your Android Toolbox
5. The User Interface: Enjoy the View
Your user interface is made up of layouts and GUI components
Three key layouts: relative, linear, and grid
RelativeLayout
LinearLayout
GridLayout
RelativeLayout displays views in relative positions
You MUST set the layout width and height
Adding padding
Positioning views relative to the parent layout
Attributes for positioning views relative to the parent layout
Positioning views relative to other views
Attributes for positioning views relative to other views
Use margins to add distance between views
RelativeLayout: a summary
How you specify a relative layout
You can position views relative to the layout of another view
You can add margins to views to increase the space around them
LinearLayout displays views in a single row or column
How you define a linear layout
A linear layout displays views in the order they appear in the layout XML
Let’s change up a basic linear layout
Here’s the starting point for the linear layout
Make a view streeeeetch by adding weight
Adding weight to one view
Adding weight to multiple views
Use gravity to specify where text appears in a view
Test drive
Using the android:gravity attribute: a list of values
Move the button to the right with layout-gravity
More values you can use with the android:layout-gravity attribute
The full linear layout code
LinearLayout: a summary
How you specify a linear layout
Views get displayed in the order they appear
Stretch views using weight
Use gravity to specify where a view’s contents appear in a view
Use layout-gravity to specify where a view appears in its enclosing space
GridLayout displays views in a grid
How you define a grid layout
Adding views to the grid layout
Let’s create a new grid layout
Here’s what we’re going to do
We’ll start with a sketch
The grid layout needs two columns
Row 0: add views to specific rows and columns
Row 1: make a view span multiple columns
Row 2: make a view span multiple columns
The full code for the grid layout
GridLayout: a summary
How you specify a grid layout
Specify which row and column each view should start in
Specify how many columns each view should span
Layouts and GUI components have a lot in common
GUI components are a type of View
Layouts are a type of View called a ViewGroup
What being a view buys you
Getting and setting properties
Size and position
Focus handling
Event handling and listeners
A layout is really a hierarchy of Views
Playing with views
Text view
Defining it in XML
Using it in your activity code
Edit Text
Defining it in XML
Using it in your activity code
Button
Defining it in XML
Using it in your activity code
Toggle button
Defining it in XML
Using it in your activity code
Switch
Defining it in XML
Using it in your activity code
Check boxes
Defining them in XML
Using them in your activity code
Radio buttons
Defining them in XML
Using them in your activity code
Spinner
Defining it in XML
Using it in your activity code
Image views
Adding an image to your project
Images: the layout XML
Using it in your activity code
Adding images to buttons
Displaying text and an image on a button
Image Button
Defining it in XML
Using it in your activity code
Scroll views
Toasts
Using it in your activity code
Your Android Toolbox
6. List Views and Adapters: Getting Organized
Every app starts with ideas
Categorize your ideas: top-level, category, and detail/edit activities
Top-level activities
Category activities
Detail/edit activities
Navigating through the activities
Top-level activities go at the top
Category activities go between top-level and detail/edit activities
Detail/edit activities
Use ListViews to navigate to data
We’re going to build part of the Starbuzz app
The top-level activity
The drinks category activity
The drink detail activity
How the user navigates through the app
The Starbuzz app structure
Here are the steps
Create the project
The Drink class
The image files
The top-level layout contains an image and a list
Use a list view to display the list of options
How to define a list view in XML
The full top-level layout code
Test drive
Get ListViews to respond to clicks with a Listener
OnItemClickListener listens for item clicks
Set the listener to the list view
What happens when you run the code
The full TopLevelActivity code
Where we’ve got to
A category activity displays the data for a single category
A ListActivity is an activity that contains only a list
How to create a list activity
android:entries works for static array data held in strings.xml
For nonstatic data, use an adapter
Connect list views to arrays with an array adapter
Add the array adapter to DrinkCategoryActivity
What happens when you run the code
Test drive the app
App review: where we’ve got to
How we handled clicks in TopLevelActivity
ListActivity implements an item click listener by default
Pass data to an activity using the ListActivity onListItemClick() method
The full DrinkCategoryActivity code
A detail activity displays data for a single record
Retrieve data from the intent
Update the views with the data
The DrinkActivity code
What happens when you run the app
The story continues
Test drive the app
Your Android Toolbox
7. Fragments: Make it Modular
Your app needs to look great on all devices
On a phone:
On a tablet:
Your app may need to behave differently too
On a phone:
On a tablet:
But that means you might duplicate code
Fragments allow you to reuse code
A fragment has a layout
The Workout app structure
Here are the steps
Create the project
The Workout class
How to add a fragment to your project
Fragment layout code looks just like activity layout code
What fragment code looks like
Adding a fragment to an activity’s layout
Passing the workout ID to the fragment
Get the activity to set the workout ID
Activity states revisited
The fragment lifecycle
Your fragment inherits the lifecycle methods
Set the view’s values in the fragment’s onStart() method
Test drive the app
What happens when you run the app
Where we’ve got to
We need to create a fragment with a list
A ListFragment is a fragment that contains only a list
How to create a list fragment
We’ll use an ArrayAdapter to set the values in the ListView
A Fragment isn’t a type of Context
The updated WorkoutListFragment code
Display WorkoutListFragment in the MainActivity layout
Test drive the app
We need to get WorkoutDetailFragment to respond to clicks in WorkoutListFragment
Wiring up the list to the detail
We need to decouple the fragment with an interface
But when will the activity say that it’s listening?
First, add the interface to the list fragment
Then make the activity implement the interface
But how do we update the workout details?
You want fragments to work with the back button
Welcome to the back stack
Don’t update—instead, replace
Using fragment transactions
The updated MainActivity code
Test drive the app
Rotating the device breaks the app
The WorkoutDetailFragment code
Phone versus tablet
On a tablet
On a phone
The phone and tablet app structures
On a tablet
On a phone
Put screen-specific resources in screen-specific folders
The different folder options
Tablets use layouts in the layout-large folder
The MainActivity phone layout
Phones will use DetailActivity to display details of the workout
The full DetailActivity code
Use layout differences to tell which layout the device is using
The revised MainActivity code
Test drive the app
Your Android Toolbox
Fragment Lifecycle Methods
8. Nested Fragments: Dealing with Children
Creating nested fragments
We’ll add a new stopwatch fragment
Fragments and activities have similar lifecycles...
... but the methods are slightly different
The StopwatchFragment code
The StopwatchFragment layout
The StopwatchFragment layout uses String values
Adding the stopwatch fragment to WorkoutDetailFragment
We need to add it programmatically
Add a FrameLayout where the fragment should appear
Then display the fragment in Java code
getFragmentManager() creates transactions at the activity lavel
Beware the back button
Nested fragments need nested transactions
Display the fragment in its parent’s onCreateView() method
The full WorkoutDetailFragment code
Test drive the app
But there’s a problem if you try to interact with the stopwatch
Why does the app crash if you press a button?
Let’s look at the StopwatchFragment layout code
The onClick attribute calls methods in the activity, not the fragment
How to make button clicks call methods in the fragment
First, remove the onClick attributes from the fragment’s layout
Make the fragment implement OnClickListener
The StopwatchFragment onClick() method
Attach the OnClickListener to the buttons
The StopwatchFragment code
Test drive the app
But there’s a problem when you rotate the device
Rotating the device re-creates the activity
What happens to the fragment when you rotate the device
onCreateView() runs AFTER the transactions have been replayed
The WorkoutDetailFragment code
Test drive the app
Your Android Toolbox
9. Action Bars: Taking Shortcuts
Great apps have a clear structure
Top-level screens
Category screens
Detail/edit screens
They also have great shortcuts
Different types of navigation
Using actions for navigation
Let’s start with the action bar
API level 11 and above
API level 7 or above
The Android support libraries
Your project may include support libraries
We’ll get the app to use up to date themes
Change MainActivity to use an Activity
Apply a theme in AndroidManifest.xml
Define styles in style resource files
Set the default theme in styles.xml
Use a Material theme on newer devices
What happens when you run the app
Test drive the app
Adding action items to the action bar
The menu resource file
The menu showAsAction attribute
Add a new action item
Inflate the menu in the activity with the onCreateOptionsMenu() method
React to action item clicks with the onOptionsItemSelected() method
Create OrderActivity
Start OrderActivity with the Create Order action item
The full MainActivity.java code
Test drive the app
Sharing content on the action bar
You share the content with an intent
Add a share action provider to menu_main.xml
Specify the content with an intent
The full MainActivity.java code
Test drive the app
Enabling Up navigation
Setting an activity’s parent
Adding the Up button
Test drive the app
Your Android Toolbox
10. Navigation Drawers: Going Places
The Pizza app revisited
Navigation drawers deconstructed
The Pizza app structure
Create TopFragment
Create PizzaFragment
Create PastaFragment
Create StoresFragment
Add the DrawerLayout
The full code for activity_main.xml
Initialize the drawer’s list
Use an OnItemClickListener to respond to clicks in the list view
The selectItem() method so far
Changing the action bar title
Closing the navigation drawer
The updated MainActivity.java code
Get the drawer to open and close
Using an ActionBarDrawerToggle
Modifying action bar items at runtime
The updated MainActivity.java code
Enable the drawer to open and close
Syncing the ActionBarDrawerToggle state
The updated MainActivity.java code
Test drive the app
The title and fragment are getting out of sync
Dealing with configuration changes
Reacting to changes on the back stack
Adding tags to fragments
Find the fragment using its tag
The full MainActivity.java code
Test drive the app
Your Android Toolbox
11. SQLite Databases: Fire Up the Database
Back to Starbuzz
Android uses SQLite databases to persist data
Where’s the database stored?
Android comes with SQLite classes
The SQLite Helper
Cursors
The SQLite Database
The current Starbuzz app structure
We’ll change the app to use a database
The SQLite helper manages your database
Create the SQLite helper
1. Specify the database
Inside a SQLite database
Storage classes and data-types
You create tables using Structured Query Language (SQL)
The onCreate() method is called when the database is created
Insert data using the insert() method
Update records with the update() method
Multiple conditions
Delete records with the delete() method
The StarbuzzDatabaseHelper code
What the SQLite helper code does
What if you need to change the database?
SQLite databases have a version number
Upgrading the database: an overview
The story continues....
How the SQLite helper makes decisions
Upgrade your database with onUpgrade()
Downgrade your database with onDowngrade()
Let’s upgrade the database
Upgrading an existing database
Add new columns to tables using SQL
Renaming tables
Delete tables by dropping them
Execute the SQL using execSQL()
The full SQLite helper code
The SQLite helper code (continued)
What happens when the code runs
Your Android Toolbox
12. Cursors and Asynctasks: Connecting to Databases
The story so far...
We’ll change the app to use the database
The current DrinkActivity code
Get data from the database with a cursor
Cursors give you access to database data
A query lets you say what records you want from the database
Specify the table and columns
Declare any conditions that restrict your selection
Other stuff you can use queries for
The SQLiteDatabase query() method lets you build SQL using a query builder
Specifying table and columns
Restrict your query by applying conditions
Applying multiple conditions to your query
You specify conditions as String values
Order data in your query
Using SQL functions in queries
SQL GROUP BY and HAVING clauses
Get a reference to the database
getReadableDatabase() versus getWritableDatabase()
getReadableDatabase()
getWritableDatabase()
The code for getting a cursor
What the code does
To read a record from a cursor, you first need to navigate to it
Navigating cursors
Getting cursor values
Finally, close the cursor and database
The DrinkActivity code
What we’ve done so far
The current DrinkCategoryActivity code
How do we replace the array data in the ListView?
A CursorAdapter reads just enough data
The story continues
A SimpleCursorAdapter maps data to views
First, create the cursor
Creating the SimpleCursorAdapter
Closing the cursor and database
The revised code for DrinkCategoryActivity
Test drive the app
Where we’ve got to
Put important information in the top-level activity
Add favorites to DrinkActivity
Add a new column to the cursor
Respond to clicks to update the database
The DrinkActivity code
Display favorites in TopLevelActivity
Display the favorite drinks in activity_top_level.xml
What changes are needed for TopLevelActivity.java
The new top-level activity code
Test drive the app
Cursors don’t automatically refresh
Change the cursor with changeCursor()
The revised TopLevelActivity.java code
Test drive the app
Databases can make your app go in sloooo-moooo....
Life is better when threads work together
What code goes on which thread?
AsyncTask performs asynchronous tasks
The onPreExecute() method
The doInBackground() method
The onProgressUpdate() method
The onPostExecute() method
The AsyncTask class
Execute the AsyncTask
The DrinkActivity.java code
A summary of the AsyncTask steps
Your Android Toolbox
13. Services: At Your Service
Services work behind the scenes
There are two types of service
The started service app
Create the project
We’re going to create an IntentService
The IntentService from 50,000 feet
How to log messages
The full DelayedMessageService code
You declare services in AndroidManifest.xml
Add a button to activity_main.xml
You start a service using startService()
Test drive the app
We want to send a message to the screen
Screen updates require the main thread
onStartCommand() runs on the main thread
The full DelayedMessageService.java code
The application context
Test drive the app
Can we improve on using Toasts?
How you use the notification service
You create notifications using a notification builder
Getting your notification to start an activity
1. Create an explicit intent
2. Pass the intent to the TaskStackBuilder
3. Get the pending intent from the TaskStackBuilder
4. Add the intent to the notification
Send the notification using the notification service
The full code for DelayedMessageService.java
What happens when you run the code
The story continues
Test drive the app
Bound services are more interactive
How the odometer app will work
The steps needed to create the OdometerService
Create a new Odometer project
How binding works
Define the Binder
Get the service to do something
The Service class has four key methods
Location, location, location...
Add the LocationListener to the service
Registering the LocationListener
Tell the activity the distance traveled
The full OdometerService.java code
Update AndroidManifest.xml
Where we’ve got to
Update MainActivity’s layout
Create a ServiceConnection
Bind to the service when the activity starts
Unbind from the service when the activity stops
Display the distance traveled
The full MainActivity.java code
What happens when you run the code
The story continues
Test drive the app
Your Android Toolbox
14. Material Design: Living in a Material World
Welcome to Material Design
CardViews and RecyclerViews
from this:
to this:
The Pizza app structure
Add the pizza data
Add the Pizza class
Add the support libraries
Create the CardView
The full card_captioned_image.xml code
RecyclerViews use RecyclerView.Adapters
Create the basic adapter
Define the adapter’s ViewHolder
Create the ViewHolders
Each card view displays an image and a caption
Create the constructor
Add the data to the card views
The full code for CaptionedImagesAdapter.java
Create the recycler view
Add the RecyclerView to the layout
Using the adapter
The PizzaMaterialFragment.java code
A RecyclerView uses a layout manager to arrange its views
Specifying the layout manager
The full PizzaMaterialFragment.java code
Get MainActivity to use the new PizzaMaterialFragment
What happens when the code runs
The story continues
Test drive the app
Where we’ve got to
Create PizzaDetailActivity
What PizzaDetailActivity.java needs to do
Update AndroidManifest.xml
The code for PizzaDetailActivity.java
Getting a RecyclerView to respond to clicks
You can listen to views from the adapter
Keep your adapters reusable
Decouple your adapter with an interface
Add the interface to the adapter
Implement the listener in PizzaMaterialFragment.java
Test drive the app
Bring the content forward
The full code for fragment_top.xml
The full code for TopFragment.java
Test drive the app
Your Android Toolbox
I. Leaving town...
A. ART: The Android Runtime
What is the Android runtime (ART)?
ART is very different from the JVM
How Android runs an APK file
Performance and size
Security
B. ADB: The Android Debug Bridge
adb: your command-line pal
Running a shell
Get the output from logcat
Copying files to/from your device
And much, much more...
C. The Emulator: The Android Emulator
Why the emulator is so slow
How to speed up your Android development
1. Use a real device
2. Use an emulator snapshot
3. Use hardware acceleration
D. Leftovers: The Top Ten Things (we didn’t cover)
1. Distributing your app
Preparing your app for release
Releasing your app
2. Content providers
3. The WebView class
4. Animation
Property animation
View animations
Activity transitions
5. Maps
6. Cursor loaders
7. Broadcast receivers
8. App widgets
9. NinePatch graphics
10. Testing
E. O’reilly®: Android Development
What will you learn from this book?
Why does this book look so different?
Index
About the Authors
Copyright
← Prev
Back
Next →
← Prev
Back
Next →