Android Programming For Developers John Horton Helder Vasconcelos
Android Programming For Developers John Horton Helder Vasconcelos
Android Programming For Developers John Horton Helder Vasconcelos
Android Programming For Developers John Horton Helder Vasconcelos
1. Android Programming For Developers John Horton
Helder Vasconcelos download
https://ebookbell.com/product/android-programming-for-developers-
john-horton-helder-vasconcelos-50654034
Explore and download more ebooks at ebookbell.com
2. Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Android Programming For Developers 1st Edition John Horton Helder
Vasconcelos
https://ebookbell.com/product/android-programming-for-developers-1st-
edition-john-horton-helder-vasconcelos-6810066
Java Programming For Android Developers For Dummies 2nd Edition Barry
Burd
https://ebookbell.com/product/java-programming-for-android-developers-
for-dummies-2nd-edition-barry-burd-50864416
Java Programming For Android Developers For Dummies 1st Edition Barry
Burd
https://ebookbell.com/product/java-programming-for-android-developers-
for-dummies-1st-edition-barry-burd-4439884
Java Programming For Android Developers For Dummies Barry Burd Burd
https://ebookbell.com/product/java-programming-for-android-developers-
for-dummies-barry-burd-burd-22908216
3. Java Programming For Android Developers For Dummies Burd Barry
https://ebookbell.com/product/java-programming-for-android-developers-
for-dummies-burd-barry-49569316
Windows Phone 7 Programming For Android And Ios Developers 1st Edition
Zhinan Zhou
https://ebookbell.com/product/windows-phone-7-programming-for-android-
and-ios-developers-1st-edition-zhinan-zhou-2349820
Windows Phone 7 Programming For Android And Ios Developers Zhinan Zhou
https://ebookbell.com/product/windows-phone-7-programming-for-android-
and-ios-developers-zhinan-zhou-5469884
Windows Phone 7 Programming For Android And Ios Developers Zhinan Zhou
https://ebookbell.com/product/windows-phone-7-programming-for-android-
and-ios-developers-zhinan-zhou-23142176
Windows Phone 7 Programming For Android And Ios Developers 1st Edition
Zhinan Zhou
https://ebookbell.com/product/windows-phone-7-programming-for-android-
and-ios-developers-1st-edition-zhinan-zhou-10602700
7. Table of Contents
Android: Programming for Developers
Android: Programming for Developers
Credits
Preface
What this learning path covers
What you need for this learning path
Windows
Mac OS X
Linux
Who this learning path is for
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Module 1
1. The First App
How Java and Android work together
The Android API
Java is object-oriented
What exactly is Android?
The development environment
A note to the existing developers who use Eclipse
The JDK
What if I already have Java?
Installing the JDK
Setting up Android Studio
What makes an Android app
Android resources
The structure of Android's Java code
Android packages
Our first Android app
8. Creating the project
A note on version controlling
Deploying and testing the app
Deploying to an emulator
Deploying to a real Android device
FAQ
Summary
2. Java – First Contact
Examining the log output
Exploring the project assets and code
Examining the layout file
Improving our app and deploying again
Modifying the UI
Meet Java
Java comments
Sending messages
Writing our first Java code
Writing our own Java methods
Examining the log output
FAQ
Summary
3. Exploring Android Studio
The Android Studio guided tour
Parts of the UI
The console
More console features
The project explorer
Transforming the editor into a design studio
E1 – the Preview toolbar
E2 – exploring the palette
E3 – the layout preview
E4 – the Component Tree
E5 – the Properties window
E6 – text and design view tabs
The project folder and file structure
FAQ
Summary
9. 4. Designing Layouts
Exploring Android UI design
Structure of a UI design
Configuring and using widgets
Widget properties
Setting the size
Sizing using dp
Sizing fonts using sp
Determining size with wrap or match
Using padding and margin
Using the layout_weight property
Using gravity
More properties
Experimenting with widgets
Containing widgets in layouts
RelativeLayout
RelativeLayout in action
Using LinearLayout
Summary
5. Real-World Layouts
Building a real-world UI
Creating a tablet emulator
List-detail layout with ScrollView and LinearLayout
Designing a form with RelativeLayout
Summary
6. The Life and Times of an Android App
Introduction to the Android lifecycle
A simplified explanation of the Android lifecycle
Lifecycle phases – what we need to know
Lifecycle phases – what we need to do
The lifecycle demonstration app
Some other overridden methods
The structure of Java code – revisited
Summary
7. Coding in Java Part 1 – Variables, Decisions, and Loops
Java is everywhere
Syntax and jargon
10. More code comments
Storing and using data with variables
Types of variables
Primitive types
Reference types
Variable declaration
Variable initialization
Changing values in variables with operators
Expressing yourself demo app
Decisions
Indenting our code
More operators
If they come over the bridge, shoot them
Else do this instead
Switching to make decisions
The Switch Demo app
Repeating code with loops
While loops
Breaking out of a loop
Continue
Do while loops
For loops
Loops demo app
Summary
8. Coding in Java Part 2 – Methods
Methods revisited
The method structure
Modifiers
Return types
The name of a method
Parameters
Working in the method body
Using methods – demo apps
Real-world methods
Exploring method overloading
Scope and variables revisited
FAQ
11. Further reading
Summary
9. Object-Oriented Programming
Important memory management warning
Introducing OOP
What is OOP exactly?
Encapsulation
Polymorphism
Inheritance
Why do it like this?
A class recap
Taking a look at the code for a class
The class implementation
Declaring, initializing, and using an object of the class
The basic classes mini app
More things we can do with our first class
Remember that encapsulation thing?
Controlling class use with access modifiers
Class access in a nutshell
Controlling variable use with access modifiers
Variable access summary
Methods have access modifiers too
A method access summary
Accessing private variables with getters and setters
Setting up our objects with constructors
Static methods
Encapsulation and static methods mini app
OOP and inheritance
The inheritance mini app
Polymorphism
Abstract classes
Interfaces
FAQ
Summary
10. Everything's a Class
All Android UI elements are classes too
Reintroducing references
12. A quick break to throw out the trash
Stack and heap – a quick summary
So, how does this heap thing help me?
Using Button and TextView widgets from our layout
Inner and anonymous classes
FAQ
Summary
11. Widget Mania
Exploring Android UI objects
Declaring and initializing objects
Widget news flash
Exploring the palette
EditText
ImageView
Radio button and group
Anonymous classes
A switch widget
CheckBox
WebView
Date & Time
Android permissions and Marshmallows
Pre-Marshmallow permissions
Marshmallow permissions
The permission solution used in this book
The Widget exploration mini app
Setting up the widget exploration project and UI
Coding the widget exploration app
Summary
12. Having a Dialogue with the User
Dialog windows
The dialog demo mini project – introducing chaining
About the Note To Self app
Using naming conventions and String resources
How to get the Note To Self code
What we will do and when we will do it
What the user can do
Building the project and gathering resources
13. Downloading the images
Preparing the String resources
Coding the Note class
Implementing the dialog designs
Coding the dialog boxes
Coding the DialogNewNote class
Coding the DialogShowNote class
Showing our new dialogs
Adding a + icon to the action bar
Summary
13. Handling and Displaying Arrays of Data
A random diversion
Handling large amount of data with arrays
Arrays are objects
A simple array example mini app
Getting dynamic with arrays
A dynamic array example
Entering the nth dimension with arrays
A multidimensional array mini app
Array out of bounds exceptions
ArrayLists
The enhanced for loop
Arrays and ArrayLists are polymorphic
ListView and BaseAdapter
The problem with displaying lots of widgets
The solution
How to use ListView and BaseAdapter
Inner classes revisited
FAQ
Summary
14. Handling and Displaying Notes in Note To Self
Note To Self continued
Updating onCreate and preparing the UI
Creating a list item for ListView
Improvements in Note To Self
Persistence
Animation
14. Sound FX
Problems with the design of the code
FAQ
Summary
15. Android Intent and Persistence
Good Intents
Switching Activity
Passing data between activities
Adding a settings page to the Note To Self app
Creating SettingsActivity
Designing the Settings screen's layout
Enabling the user to switch to the Settings screen
Persisting data with SharedPreferences
Making the Note To Self app's settings persist
Coding the SettingsActivity class
Coding the MainActivity class
Specifying a parent Activity
More advanced persistence
What is JSON?
Java exceptions - try, catch, and finally
Backing up user data in Note To Self
FAQ
Summary
16. UI Animations
Animations in Android
Designing cool animations in XML
Fading in and out
Movement
Scaling or stretching
Controlling the duration
Rotating animations
Repeating animations
Combining animation properties with a set tag
Instantiating animations and controlling them with Java code
More animation features
Listeners
Animation interpolators
15. The Animations Demo app – introducing SeekBar
Laying out the animation demo
Coding the XML animations
Wiring up the Animations Demo app in Java
Adding animations to Note To Self
Defining the animations in XML
Controlling the animations in Java
FAQ
Summary
17. Sound FX and Supporting Different Versions of Android
Supporting multiple versions of Android
Detecting the current Android version
The SoundPool class
Building SoundPool the new way and the old way
Loading sound files into memory
Playing a sound
Stopping a sound
Introducing the Spinner widget
Making sound FX
Laying out Sound Demo UI
Coding the Sound Demo app
Sound FX touches to Note To Self
Deleting a note – introducing OnLongClick
FAQ
Summary
18. Design Patterns, Fragments, and the Real World
Introducing the model-view-controller pattern
The model
The view
The controller
The imperfections of Note To Self revisited
Android design guidelines
Real-world apps
The device detection mini app
Configuration qualifiers
Using configuration qualifiers – mini app
The configuration qualifier's summary
16. Fragments
Fragments have a lifecycle too
onCreate
onCreateView
onAttach and onDetach
onStart, onPause, and onStop
Managing Fragments with FragmentManager
Our first working Fragment mini app
Fragment reality check
FAQ
Summary
19. Using Multiple Fragments
Using singletons for the model layer
Inter-Fragment communications – interfaces revisited
The dual-Fragment address book mini app
Getting started
Alias resources
The NameAndAddress class
Creating the communication interface
Explaining the structure of the onListItemSelected method
Explaining the code that starts a new Activity
Explaining the code when the detail Fragment is already present
What do we need to do?
Creating the AddressDetailFragment class and layout
Coding PortraitDetailActivity and the layout
FAQ
Summary
20. Paging and Swiping
Building an image gallery/slider app
Implementing the layout
Coding the PagerAdapter class
Coding the MainActivity class
Running the gallery app
Building a Fragment pager/slider app
Coding the SimpleFragment class
fragment_layout
Coding the MainActivity class
17. The activity_main layout
Running the Fragment slider app
Summary
21. Navigation Drawer and Where It's Snap
Introducing the navigation drawer
The Where it's snap app
Preparing the resources
Placeholder code for three Fragments
Coding the MainActivity class and layout
Switching between Fragments
Setting up the drawer
Handling the back button
Summary
22. Capturing Images
Capturing images using the camera
The capturing images mini app
Adding the camera permission to the manifest
Defining a simple layout
Coding the MainActivity class
Running the Simple Photo app
Where it's snap – coding the capture Fragment
Creating the layout for the capture Fragment
Coding the capture Fragment
Testing the capture Fragment
Summary
23. Using SQLite Databases in Our Apps
Database 101
What is a database?
What is SQL?
What is SQLite?
The SQL syntax primer
The SQLite example code
Creating a table
Inserting data into the database
Retrieving data from the database
Updating the database structure
The Android SQLite API
18. SQLiteOpenHelper and SQLiteDatabase
Building and executing queries
Database cursors
The database mini app
Implementing the layout
Coding the database class
Coding MainActivity
Running the mini app
Summary
24. Adding a Database to Where It's Snap
The Photo class
Handling the SQLite database
Saving a new photo from the capture fragment
Displaying a photo from the database
Preparing the View layout
Coding the ViewFragment class
Coding the communications interface
Coding TitlesFragment
Coding TagsFragment
Coding the fragment communications in MainActivity
Running the app so far
Summary
25. Integrating Google Maps and GPS Locations
Global Positioning System
Where in the world – the GPS mini app
Where in the world – implementing a simple layout
Coding the Where in the world mini app
Running the Where in the world mini app
The Google Maps mini app
Preparing to connect to Google Maps
Acquiring an API key
Installing the Google Play services API
Coding the maps_activity layout
Coding MapsActivity
Running the Simple Map app
Summary
26. Upgrading SQLite – Adding Locations and Maps
19. Adding locations and maps to Where it's Snap
Updating the database
Adding member variables to represent location data
Updating the database version
Adding code in onUpgrade to upgrade the database for existing users
Updating the database creation code in onCreate for new users
Updating the addPhoto method to handle GPS coordinates
Updating the Photo class
Updating CaptureFragment
Updating ViewFragment
Adding location permissions
Testing the new map feature
Summary
27. Going Local – Hola!
The Localization mini app
Preparing the layout
Preparing the first strings.xml file
Making the app multilingual with the second strings.xml file
Adding a third language
Running the app
Localizing the Where it's snap app
Summary
28. Threads, Touches, Drawing, and a Simple Game
Threads
Problems with threads
Drawing with canvas and paint
The Android coordinate system
Android Canvas demo app
Handling touches
A simple game engine
Building a simple game of Pong
Adding sound files to the project
Coding the ball
Coding the paddle
Coding MainActivity
Coding SurfaceView
Coding the update method
20. Coding the draw method
Lock the screen orientation and make it fullscreen
Running the game
Pong enhancements
Summary
29. Publishing Apps
Preparing to publish
Creating an app icon
Preparing the required resources
Building the publishable APK file
Publishing the app
Marketing
More to see
Summary
2. Module 2
1. Asynchronous Programming in Android
Android software stack
Dalvik runtime
ART runtime
Memory sharing and Zygote
Android process model
Process ranks
Process sandboxing
Android thread model
The main thread
The Application Not Responding (ANR) dialog
Maintaining responsiveness
Concurrency in Android
Correctness issues in concurrent programs
Liveness issues in concurrent programs
Thread coordination
Concurrent package constructs
Executor framework
Android primary building blocks
Activity concurrent issues
Manipulating the user interface
Service concurrent issues
21. Started services issues
Bound services issues
Service in a separate process
Broadcast receiver concurrent issues
Android concurrency constructs
Summary
2. Performing Work with Looper, Handler, and HandlerThread
Understanding Looper
Understanding Handler
Sending work to a Looper
Scheduling work with post
Using Handler to defer work
Leaking implicit references
Leaking explicit references
Updating the UI with Handler
Canceling a pending Runnable
Scheduling work with send
Cancelling pending messages
Composition versus inheritance
Multithreading with Handler and ThreadHandler
Looper message dispatching debugging
Sending messages versus posting runnables
Applications of Handler and HandlerThread
Summary
3. Exploring the AsyncTask
Introducing AsyncTask
Declaring AsyncTask types
Executing AsyncTasks
Providing indeterministic progress feedback
Providing deterministic progress feedback
Canceling an AsyncTask
AsyncTask Execution State
Handling exceptions
Controlling the level of concurrency
Common AsyncTask issues
Fragmentation issues
Memory leaks
22. Activity lifecycle issues
Handling lifecycle issues with early cancellation
Handling lifecycle issues with retained headless fragments
Applications of AsyncTask
Summary
4. Exploring the JobScheduler API
Introduction to JobScheduler
Setting running criteria
Scheduling a job
Implementing the JobService
Listing pending jobs
Canceling a job
Scheduling a periodic job
Applications of the JobScheduler
Summary
5. Interacting with the Network
Introducing Android HTTP clients
AndroidHttpClient
HttpURLConnection
Performing HTTP requests asynchronously
Retrieving a text response
Interacting with JSON web APIs
Converting Java objects to JSON
Interacting with XML web APIs
Converting Java objects to XML
Converting XML to Java objects
Customizing HTTP timeouts
Communicating securely over SSL sessions
Summary
6. Network Interactions with GCM
Introduction to GCM
Setting up and configuring GCM for your application
Registering the GCM Receiver
Setting up a registration service
InstanceID listener
Receiving downstream messages
Receiving messages from topic
23. Sending upstream messages
GcmListenerService delivery callbacks
Executing tasks with GCM Network Manager
Building a one shot task
Summary
7. Asynchronous Programing with RxJava
Introduction to RxJava
Cold versus Hot Observable
RxJava setup
Creating Observables
Transforming Observables
Understanding Schedulers
Performing IO operations with Schedulers
Canceling subscriptions
Composing Observables
Monitoring the event stream
Combining Observables
Observing UI Events with RxJava
Working with Subjects
Summary
3. Module 3
1. Setting Up the Project
The right tool for the right game
Do you want to use 3D?
Do you want to use physics?
Do you want to use Java?
Pros of building games with the Android SDK
Cons of building games with the Android SDK
I want the Android SDK!
The project – YASS (Yet Another Space Shooter)
Activities and Fragments
Project setup
Creating the stub project
Cleaning up
Choosing an orientation
Dealing with aspect ratios
Game architecture
24. GameEngine and GameObjects
Starting a game
Stopping a game
Managing game objects
UpdateThread
DrawThread
User input
Putting everything together
Moving forward with the example
Handling the back key
Honoring the lifecycle
Using as much screen as we can
Before Android 4.4 – almost fullscreen
Android 4.4 and beyond – immersive mode
Putting fullscreen together
Good practices for game developers
Object pools
Avoiding enhanced loop syntax in lists
Precreating objects
Accessing variables directly
Being careful with floating points
Performance myths – avoid interfaces
Summary
2. Managing User Input
The InputController base class
The Player object
Displaying a spaceship
Firing bullets
The Bullet game object
The most basic virtual keypad
Limitations and problems
Creating a virtual joystick
General considerations and improvements
Physical controllers
Handling MotionEvents
Handling KeyEvents
Detecting gamepads
25. Sensors and InputControllers
Selecting control modes
Summary
3. Into the Draw Thread
Using GameView
The GameView interface
StandardGameView
SurfaceGameView
Updating GameEngine
Updating the game layout
Improving DrawThread
Sprites
Updating the spaceship and bullets
Adding a frames-per-second (fps) counter
Spawning enemies – the GameController
Procedural/random
Deterministic/static
Hybrid approach
Our approach
The asteroids
More on the transformation matrix
Occlusion culling
Parallax backgrounds
Multiple backgrounds
Layers
Summary
4. Collision Detection
Detecting collisions
Who can collide?
Updating GameEngine
Handling collisions
Rectangular bodies
Adding visual feedback
Pros and cons
Circular bodies
Adding visual feedback
Pros and cons
26. Mixed collision detection
Adding visual feedback
Other options for shapes
Optimization
Spatial partitioning and QuadTree
Duplicated collisions
Summary
5. Particle Systems
General concepts
Particles
ParticleSystem
Initializers
Modifiers
Composite GameObjects and GameEngine
Making good particle systems
One shot
Asteroid explosions
Spaceship explosions
Emitters
Asteroid trails
The spaceship's engine
Summary
6. Menus and Dialogs
Custom fonts
Working with backgrounds
The power of XML drawables
State list drawables
State lists colors
Shape drawables
The GameFragment
Adding a score
Adding lives
Custom dialogs
BaseCustomDialog
Quit dialog
Pause dialog
Game Over dialog
27. Other dialogs
Designing for multiple screen sizes
Summary
7. To the Big Screen
Project configuration
Testing for Android TV
Declaring a TV Activity
Providing a home screen banner
Declaring it as a game
Declaring Leanback support
Declaring touchscreen capability as not required
Reviewing the manifest
Showing controller instructions
Dealing with overscan
Controller-based navigation
Dialogs and controllers
Beyond this book
Summary
A. Bibliography
Index
31. Credits
Authors
John Horton
Helder Vasconcelos
Raul Portales
Reviewers
Nayanesh Ramchandra Gupte
Klaas Kabini
Márton Kodok
Paresh Mayani
Gavin Matthews
Sergio Viudes Carbonell
Antonio Hernández Niñirola
Content Development Editor
Rohit Kumar Singh
Graphics
Abhinash Sahu
Production Coordinator
Aparna Bhagat
32. Preface
Do you have a great idea for an app, but don't know how to make it a reality?
Are you trying to start a career in programming, but haven't found the right way
in? We will help you get to grips with Android programming concepts and
develop your own applications. Whether you are Android beginner developer or
an Android seasoned programmer, this course will explore how to achieve
efficient and reliable multithreaded Android applications. We'll look at best
asynchronous constructs and techniques, commonly used by Android Developer
community, to execute computation intensive or blocking tasks off the main
thread, keeping the UI responsive, telling the user how things are going, making
sure we finish what we started, using those powerful multicore processors, and
doing it all without wasting the battery. You will learn all the aspects of
developing a game using a space shooter game as the example that will evolve
with you throughout the chapters.
33. What this learning path covers
Module 1, Android Programming for Beginners, introduces you to the
fundamental concepts of Android programming. At the completion of this
module, you will be ready to start building your own custom applications in
Android and Java Module 2, Asynchronous Android Programming, will help you
learn how to manage interactions between several threads and avoid concurrency
and synchronization problems will help you build well-behaved applications
with smooth, responsive user-interfaces that delight users with speedy results
and data that's always fresh.
Module 3, Mastering Android Game Development, will guide you to build a
real-time game from scratch using the Android SDK. Starting with the creation
of a game engine and moving into handling user input, doing efficient drawing,
implementing collision detection, playing sound effects, using animations, and
so on.
34. What you need for this learning path
Android Studio running on any of the major operating systems can use the code
in this course. Android Studio is a free software and full setup instructions for
Windows are in the opening chapter. Android Studio is the recommended
development tool, and at the time of publication, the minimum system
requirements were as follows:
35. Windows
Microsoft® Windows® 8/7/Vista/2003 (32 or 64 bit)
2 GB RAM minimum; however, 4 GB RAM is recommended
400 MB hard disk space
At least 1 GB for Android SDK, emulator system images, and caches
1280 x 800 minimum screen resolution
Java Development Kit (JDK) 7
Optional for accelerated emulator: Intel® processor with support for Intel®
VT-x, Intel® EM64T (Intel® 64), and Execute Disable (XD) Bit
functionality
36. Mac OS X
Mac® OS X® 10.8.5 or a higher version, up to 10.9 (Mavericks)
2 GB RAM minimum; however, 4 GB RAM is recommended
400 MB hard disk space
At least 1 GB for the Android SDK, emulator system images, and caches
1280 x 800 minimum screen resolution
Java Runtime Environment (JRE) 6
Java Development Kit (JDK) 7
Optional for accelerated emulator: Intel® processor with support for Intel®
VT-x, Intel® EM64T (Intel® 64), and Execute Disable (XD) Bit
functionality
On a Mac OS, run Android Studio with Java Runtime Environment (JRE) 6 for
optimized font rendering. You can then configure your project to use Java
Development Kit (JDK) 6 or JDK 7.
37. Linux
A GNOME or KDE desktop
GNU C Library (glibc) 2.15 or later
2 GB RAM minimum; however, 4 GB RAM is recommended
400 MB hard disk space
At least 1 GB for the Android SDK, emulator system images, and caches
1280 x 800 minimum screen resolution
Oracle® Java Development Kit (JDK) 7
Tested on Ubuntu® 14.04, Trusty Tahr (64-bit distribution capable of running
32-bit applications).
For module 2, to follow along and experiment with the examples, you will need
a development computer with a Java 7 (or 8) SE Development Kit and the
Android Software Development Kit Version 9 or above (you will need at least
Version 21 to try all of the examples).
You will also need Android Studio IDE. The examples have been developed
using Google's new Android Studio IDE and use its integrated build system,
Gradle. While you can run the examples using the emulator provided by the
Android SDK, it is a poor substitute for the real thing. A physical Android
device is a much faster and more pleasurable way to develop and test Android
applications! Many of the examples will work on a device running any version
of Android since 2.3, GingerBread. Some examples demonstrate newer APIs and
as a result, require a more recent Android version—up to Android 5, Lollipop.
Specifically for module 3, you will need the latest version of Android Studio and
the Android SDK for Lollipop or newer (API level 22) versions, which you can
download using Android Studio.
38. Who this learning path is for
If you are an iOS developer or any other developer/programmer and you want to
try your hands on developing applications on the Android platform, this course
is for you. No prior programming experience is needed as this course will guide
you right from the beginning to the advanced concepts of Android programming.
39. Reader feedback
Feedback from our readers is always welcome. Let us know what you think
about this course—what you liked or disliked. Reader feedback is important for
us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <feedback@packtpub.com>, and
mention the course's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either
writing or contributing to a book, see our author guide at
www.packtpub.com/authors.
40. Customer support
Now that you are the proud owner of a Packt course, we have a number of things
to help you to get the most from your purchase.
41. Downloading the example code
You can download the example code files for this course from your account at
http://www.packtpub.com. If you purchased this course elsewhere, you can visit
http://www.packtpub.com/support and register to have the files emailed directly
to you.
You can download the code files by following these steps:
1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the course in the Search box.
5. Select the course for which you're looking to download the code files.
6. Choose from the drop-down menu where you purchased this course from.
7. Click on Code Download.
You can also download the code files by clicking on the Code Files button on
the course's webpage at the Packt Publishing website. This page can be accessed
by entering the course's name in the Search box. Please note that you need to be
logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the
folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the course is also hosted on GitHub at
https://github.com/PacktPublishing/Android-Programming-for-Developers. We
also have other code bundles from our rich catalog of books, videos, and course
available at https://github.com/PacktPublishing/. Check them out!
42. Errata
Although we have taken every care to ensure the accuracy of our content,
mistakes do happen. If you find a mistake in one of our courses—maybe a
mistake in the text or the code—we would be grateful if you could report this to
us. By doing so, you can save other readers from frustration and help us improve
subsequent versions of this course. If you find any errata, please report them by
visiting http://www.packtpub.com/submit-errata, selecting your course, clicking
on the Errata Submission Form link, and entering the details of your errata.
Once your errata are verified, your submission will be accepted and the errata
will be uploaded to our website or added to any list of existing errata under the
Errata section of that title.
To view the previously submitted errata, go to
https://www.packtpub.com/books/content/support and enter the name of the
course in the search field. The required information will appear under the Errata
section.
43. Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all
media. At Packt, we take the protection of our copyright and licenses very
seriously. If you come across any illegal copies of our works in any form on the
Internet, please provide us with the location address or website name
immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the suspected
pirated material.
We appreciate your help in protecting our authors and our ability to bring you
valuable content.
44. Questions
If you have a problem with any aspect of this course, you can contact us at
<questions@packtpub.com>, and we will do our best to address the problem.
45. Part 1. Module 1
Android Programming for Beginners
Learn all the Java and Android skills you need to start making powerful
mobile applications
46. Chapter 1. The First App
Welcome! In this chapter, we won't waste any time in getting started with
developing Android apps.
We will look at what is so great about Android, what Android and Java are
exactly, how they work and complement each other, and what this means to us
as future developers.
After this, we will spend a little time setting up our development environment
and then get straight to building and deploying our first app.
By the end of this chapter, we will have done the following:
Set up the Java Development Kit (JDK), part of the required Android
development environment
Installed Android Studio, the final part of our Android development
environment
Built our very first Android app
Deployed an Android emulator
Run our app on an Android emulator and a real device
47. How Java and Android work together
After we write a program in Java for Android, we click on a button to change
our code into another form that is understood by Android. This other form is
called Dalvik EXecutable (DEX) code, and the transformation process is called
compiling. Compiling takes place on the development machine after we click on
that button. We will see this work right after we set up our development
environment.
Android is a fairly complex system, but you do not need to understand it in depth
to be able to make amazing apps. The part of the Android system that executes
(runs) our compiled DEX code is called the Dalvik Virtual Machine (DVM).
The DVM itself is a piece of software written in another language that runs on a
specially adapted version of the Linux operating system. So what the user sees of
Android, is itself just an app running on another operating system.
The purpose of the DVM is to hide the complexity and diversity of the hardware
and software that Android runs on but, at the same time, its purpose is to expose
all of its useful features. This exposing of features generally works in two ways.
The DVM itself must have access to the hardware, which it does, but this access
must be programmer friendly and easy to use. The way the DVM allows us
access is indeed easy to use because of the Android Application Programming
Interface (API).
48. The Android API
The Android API is the code that makes it really easy to do exceptional things. A
simple analogy could be drawn with a machine, perhaps a car. When you step on
the accelerator, a whole bunch of things happen under the hood. We don't need
to understand about combustion or fuel pumps because a smart engineer has
provided an interface for us. In this case, a mechanical interface—the
accelerator pedal.
Take the following line of Java code as an example; it will probably look a little
intimidating if you are completely new to Android:
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
However, once you learn that this single line of code searches for the available
satellites and then communicates with them in orbit around the Earth while
retrieving your precise latitude and longitude on the planet, it is easy to begin to
glimpse the power and depth of the Android API in conjunction with the DVM.
Even if that code does look a little challenging at the moment, imagine talking to
a satellite in some other way!
The Android API is mainly a whole bunch of Java code. So, how do we use all
this code to do cool stuff without getting swamped by its complexity? How do
we find and manipulate the pedals, steering wheel, and sunroof of the Android
API?
Note
There are many different estimates to the number of lines of code that have gone
into Android. Some estimates are as low as 1 million, some as high as 20
million. What might seem surprising is that, despite this vast amount of code,
Android is known in programming circles for being "lightweight".
49. Java is object-oriented
Java is a programming language that has been around a lot longer than Android.
It is an object-oriented language. This means that it uses the concept of reusable
programming objects. If this sounds like technical jargon, another analogy will
help. Java enables us and others (such as the Android development team) to
write Java code that can be structured based on real-world "things" and, here is
the important part, it can be reused.
So, using the car analogy, we could ask the question: if a manufacturer makes
more than one car in a day, do they redesign each and every part for each and
every car?
The answer, of course, is no. They get highly skilled engineers to develop
exactly the right components that are honed, refined, and improved over years.
Then, that same component is reused again and again, as well as occasionally
improved. Now, if you are going to be picky about my analogy, then you can
argue that each of the car's components still have to be built from raw materials
using real-life engineers, or robots, and so on.
This is true. What the software engineers actually do when they write their code
is build a blueprint for an object. We then create an object from their blueprint
using Java code and, once we have that object, we can configure it, use it,
combine it with other objects, and more. Furthermore, we can design blueprints
and make objects from them as well. The compiler then translates
(manufactures) our custom-built creation into DEX code.
In Java, a blueprint is called a class. When a class is transformed into a real
working thing, we call it an object.
Note
Objects in a nutshell
We could go on making analogies all day long. As far as we care at this point:
Java is a language that allows us to write code once that can be used over
and over again.
This is very useful because it saves us time and allows us to use other
50. people's code to perform tasks we might otherwise not have the time or
knowledge to write for ourselves.
Most of the time, we do not even need to see this code or even know how it
does its work!
One last analogy. We just need to know how to use that code, just as we only
need to learn to drive the car.
So, a smart software engineer up at Google HQ writes a desperately complex
Java program that can talk to satellites. He then considers how he can make this
code useful to all the Android programmers out there. One of the things he does
is he makes features such as getting the device's location in the world a simple
one-line task. So the one line of code we saw previously sets many more lines of
code in action that we don't see. This is an example of using somebody else's
code to make our code infinitely simpler.
51. What exactly is Android?
We know that to get things done on Android, we write Java code of our own,
which also uses the Java code of the Android API. This is then compiled into
DEX code and run by the DVM, which in turn has connections to an underlying
operating system called Linux.
Then the manufacturers of the Android devices and individual hardware
components write advanced software called drivers, which ensure that their
hardware (CPU, GPU, GPS receivers, and so on) can run on the underlying
Linux operating system.
Our compiled Java code, along with some other resources, is placed in a bundle
of files called an Android application package (APK), and this is what the
DVM needs to run our app. This process is explained in the following figure:
In summary, all we need to do is learn how to read and code Java, so we can
begin to learn and take advantage of the Android API.
All these tools are free, so let's take a look at the development environment we
will be using.
52. The development environment
A development environment is a term that refers to having everything you need
in order to develop, set up, and be ready to go in one place. We need the
following two things to get started:
We talked a fair bit about compiling our Java code, as well as other people's
Java code, into DEX code that will run on the DVM, on people's Android
devices. In order to use Java code, we need a free software called the JDK.
The JDK also includes other people's code, which is separate from the
Android API.
There is a whole range of tools that are required to develop for Android,
and we also need the Android API, of course. This whole suite of
requirements is collectively known as the Android software development
kit (SDK). Fortunately, downloading and installing a single application will
give us these things all bundled together. This single application is called
Android Studio.
Android Studio is an integrated development environment (IDE) that takes
care of all the complexities of compiling our code and linking with the JDK and
the Android API. Once we have installed the JDK and Android Studio, we can
do everything we need inside this application.
Tip
What could possibly go wrong?
I got a lot of feedback via my website http://gamecodeschool.com about a
previous book of mine that showed how to install an Android development
environment. People said that setting this up can be the hardest part. So I've
written this section to be as thorough as possible because not everybody has a
smooth setup experience.
Hopefully, you won't need all the extra tips and detailed figures, but there are a
few vagaries that can trip us up while setting up the development environment.
Most likely, these instructions will get you up and running quickly and cover all
your issues. If there is an issue that I haven't managed to anticipate, don't let it
beat you! I guarantee that you are not the first to have that exact issue. Perform a
53. beat you! I guarantee that you are not the first to have that exact issue. Perform a
web search (use Google), be really specific in your search criteria, and I am
confident you will be coding in no time at all.
This guide will get around 99% of the Windows user's setup in a couple of
hours. All the coding and development information you need will be covered
100% step by step.
For Mac and Linux users, most of these instructions can be easily interpreted as
the key points of the tutorial are more about what we do inside of the setup
programs and less about the specific environment we are using. My apologies
for not providing comprehensive instructions for every operating system.
54. A note to the existing developers who use
Eclipse
There are multiple options regarding which software to use when developing
Android apps. In the early days of developing Android, an IDE called Eclipse
was most commonly used. A few years ago, a new "official" contender for the
best Android IDE was released. This was Android Studio. The problem after its
first release was that it was still in the beta (not finished) stage. It had numerous
bugs, including some quite awkward ones. However, even then it was the
preferred IDE for many because of its smooth operation, cool looks, official
status, and prestigious heritage.
Now that Android Studio has exceeded version 1, there is virtually no reason to
use anything else, especially if you are just getting started with Android. If you
already have Eclipse set up for Android development and really don't want to
change, that's fine, the code in this book will work. However, there will be
significant differences in the instructions, especially regarding the user interface
(UI) designer. Also, the code in this book has been thoroughly tested by others
and me in Android Studio.
The sections that follow will set up a development environment with the JDK
and Android Studio as our IDE of choice.
56. Sir—I have been all day down at the scene of the wreck of the
Dunbar, and had a long interview with Johnson, the man who was
saved. If the statement he made to me, and which I carefully noted,
be of any service to you as information of a correct character for the
public, who all feel a deep interest in this melancholy event, I shall
be glad that I have taken this course to forward it. He stated that
they were off Botany at half-past eight o'clock p.m., Thursday; the
captain then stood off shore, on the starboard tack, ship with
double-reefed fore and main topsails; a very dirty dark, and rainy
night, two men were placed at the wheel; Captain Green instructed
them to keep their luff; he (Captain Green) had not been off the
deck for two hours since they first made land, some days previously;
at half-past eleven p.m., the captain gave orders to square away,
which was done; the ship then ran under close-reefed fore and main
topsails and foresail. As they neared the "light" the captain ordered
the foresail to be clewed up, sent the second mate to the foresail to
keep a look-out, then very dark; told him to "keep a good look-out
for the North Head." The captain asked if he could see the Head.
The mate replied no, it was solid darkness. The second mate
suddenly called out "Breakers a-head." The captain ordered the helm
to be put hard to starboard to bring the ship round, then blowing
strong; ship on a dead lee shore, having such small sail upon her,
the ship would not come round, (this was about 12 o'clock), and the
sea lifting her in, she almost immediately struck; the passengers,
who had been in bed, rushed up on deck in their night dresses; their
shrieks were dreadful (Johnson describes the scene at this time the
most terrible part of the whole; the ladies asked the captain, and
entreated the seamen to know if there was any hope; the ship was
still holding together, and the men thought and said there was
hope.) Almost immediately after, as if in angry denial of that
expression, the decks burst up from the pressure of the water, the
ship was rent into a thousand pieces, and all on board (except him)
were hurried into the foaming terrific sea.
57. THE SAILOR RESCUED.
Johnson, with the old boatswain, and two Dutch seamen, were
about the last who were washed from the wreck, they four holding
on a piece of plank, from which the two Dutchmen were soon after
washed; a huge sea then threw Johnson and the boatswain on shore
amongst some pieces of timber, from which Johnson scrambled to a
higher shelving rock to avoid the next sea, which he did, but the
poor old boatswain, less active, was carried way, and perished.
Johnson then climbed to a still higher position, and, being much
exhausted, laid down and slept. The next day he saw a steamer (the
Grafton) go into the Heads; he made signals to her, but was not
58. seen. During the day he saw another steamer (the Washington)
pass, and tried to attract her attention; as, also, that of a schooner
running in. Friday night was passed in this state. On Saturday
morning he endeavoured to get along the rocks; he could see people
on the cliffs above, but could not make himself seen, until a brave
lad, (Antonio Wollier, an Icelander,) who had gone down "Jacob's
Ladder," and along the rocks, noticed Johnson waving a
handkerchief; relief came, and he was soon after hauled up to the
top of the cliffs, which are there about 200 feet high.
The noble fellow, Wollier, was then hauled up, and received the
hearty manifestations of the thousands there assembled. I opened a
subscription, which was suggested by Captain Loring, of H.M. ship
Iris, and in a few minutes, about £10 was collected, and handed
over to the courageous boy, who, in answer to my compliment when
handing him the money, said, in broken English, "He did not go
down for the money, but for the feelings of his heart."
Johnson says that a blue light was burned when the ship struck, but
it was very dim, and could scarcely be seen; Captain Green must
have taken the bluff north end of the Gap for the North Head, for, in
ordering the helm to starboard, he must have supposed that to have
been his position, and North Head a lee shore; for had the helm
been put to port, the ship would have cleared, and run for the
entrance to the Heads.
Afterwards, at the "Gap," another brave fellow, whose name I have
not yet learned, volunteered to go down to send up some of the
mangled corpses, now and then lodging on the rocks beneath us—
now a trunk of a female, from the waist upwards—then the legs of a
male, the body of an infant, the right arm, shoulder, and head of a
female, the bleached arm, and extended hand, with the wash of the
receding waters almost as 'twere in life, beckoning for help! then a
leg, a thigh, a human head would be hurled along, the sea dashing
most furiously, as if in angry derision of our efforts to rescue its
prey; one figure, a female, tightly clasping an infant to the breast,
both locked in the firm embrace of death, was for a moment seen,
59. then the legs of some trunkless body would leap from the foaming
cataract, caused by the receding sea, leaping wildly, with feet seen
plainly upward in the air, to the abyss below, to be again and again
tossed up to the gaze of the sorrowing throng above.
We procured a rope, lowered the man, with some brave stout hearts
holding on to the rope above, and in this manner several portions of
the mutilated remains were hauled up to the top of the cliff, until a
huge sea suddenly came, and nearly smothered those on the cliff,
wetting them all to the skin. I caused the man to be hauled up,
thinking it too dangerous to continue. It was a heartrending scene
and I was glad to leave it, which I did soon after, and returned to
Sydney about dark.
Wonderful to say, Johnson has not as much as a scratch about him,
and is otherwise quite well. He states that there were a great many
bodies near to one place where he was rescued, and his great fear
was that he would be starved. The ship was eighty-one days out.
Saturday evening.
THE INQUEST.
At nine o'clock a.m. (on the 24th), Captain M'Lerie attended by a
body of Inspectors and several other persons repaired to the Dead
House, and began the harrowing task of attempting to identify the
bodies.
A large crowd surrounded the place, who unfeignedly, so far as
deportment and general appearance went, sympathised with the
mourners who sought among the mutilated remains inside for
relatives and friends. This continued up to eleven o'clock, when all
that it was possible to identify were marked off, and in some cases
given to their friends, the remainder with the unknown and
unrecognisable being placed in shells and viewed by the jury already
60. sworn on the inquest. These gentlemen, attended by the coroner,
assembled in the large room of the King's Arms (Mrs. Stone's), a
little after eleven, for the purpose of resuming the inquiry adjourned
from yesterday morning.
Thirteen gentlemen had been sworn on the jury, and these all
attended, Mr. J. V. Gorman being foreman. The first witness called
was—
James Johnson, seaman, late of the Dunbar, being sworn, stated,
Belonged to the Dunbar, commanded by Captain Green. We sailed for
Plymouth first; the Dunbar, is a first-class Ship; we sailed from
Plymouth on the 31st May, with general cargo; would not say how
many passengers—there were cabin passengers, male and female;
there were also second-class passengers, male and female, on
board; I cannot state the exact number on board; am positive of the
day of sailing; we sailed on Sunday morning; there were fifty-nine
seamen on the ship's articles, including captain, officers, able-bodied
seamen, boys, and all; the chief officer's name was Mr. Struthers; we
had a prosperous voyage till we reached the coast of New Holland;
we first made King's Island a week last Sunday, the 16th August, the
wind fresh and blowing from west, under double-reefed topsails; we
had been looking out for land, and we made it out according to the
captain's calculation; there was a watch kept on deck, and time
called every half-hour; King's Island was the land we first expected
to make; we saw the island very plain; when first seen the wind was
from the westward; we then shaped our course for the Straits; from
where we made the land the weather was thick, wet, and hazy; the
sails were shortened from stress of weather; two reefs of the topsail
were taken; we did not shorten sail to meet the land; I cannot
exactly say what was the course we shaped; we made the Straits
that night, the 16th; King's Island was the land we were looking out
for before; we made it according to the captain's calculation, and
saw the island very plain; the wind, at this time, was from the
westward; we then shaped our course through the Straits; from the
time we made the land the weather was thick and squally the whole
61. time, and sail was shortened from stress of weather; our course was
somewhere to the east, but I cannot say the point we steered
exactly; we made the Straits that same night; we saw a light about
two o'clock the next morning that was said to be upon some land in
the middle of the Straits; we also saw the land; we did not alter our
course; the light was rather on our port bow; no change took place
till next day, when the wind headed us, and we made two boards
which carried us clear of the islands, I have never been here before,
but I have been in Melbourne; I am an able seaman, and have been
eleven years at sea; I served my time on the coast of England, out
of Lancashire, principally trading between England and Ireland; after
we passed Kent's Group the next land we saw was the light at Cape
Howe; I was told that was the Cape Howe light; we made this light
in the evening; I do not know that there was any change of course;
we were under double reefed topsails, with all the yards braced
sharp up; there was no great stress of weather at the time; it was
thick, hazy weather; we saw the land at times, but not always; there
was no heavy sea on; a correct look-out was kept from the time we
made the land; a person was stationed forward, but there was no
look-out from aloft; I have never seen looks-out from aloft in ships
that I have been in; we carried the same sail throughout until we
made the land at Botany; this was on the Thursday evening: all
hands saw the land distinctly; after that the Captain ordered us to
close reef the topsails, and we were close hauled to the wind; the
wind was then about E. and by S.; we were close to the wind and
lying about N.E. and by N., and lying along the coast; at the time we
made this land to the best of my opinion we were about ten or
twelve miles off, and the ship had her starboard tacks aboard; we
were under easy sail, sail having been shortened after we saw the
land; we had on no topgallant-sails, and we had three reefs in the
main, and four reefs in the fore-topsail; the mizen-topsail was
stowed, and the spanker was brailed up; the inner jib, and the
maintopmast-staysail, were taken in; the weather was squally with
thick rain; when we made the land at Botany, we kept on our
course; this was between six and seven o'clock, and when night
came on, we still kept our course, and shortly afterwards we saw the
62. Sydney light; I saw it about seven o'clock, shortly after getting
supper; it was known to be the Sydney Head light; the vessel was
then lying a course about N.E. and by N.; she was lying her course
in that sort of manner that we had no difficulty—we had plenty of
room; she was not at all labouring with the sail she had on; I know
that she was making heavy lee-way; it is my impression that she had
not got enough sail on her, to prevent her making this lee-way; this
was not said on board ship, but I think so; Captain Green was on the
deck; they were not shaking the ship up into the wind, but keeping
her clear full; the Captain was not conning the ship; the chief officer
was on the poop likewise; the watch on deck went below according
to orders, and were relieved at eight o'clock; it was raining hard; the
light was only seen at intervals, but distinctly; it is a revolving light; I
was on deck at eight o'clock, as I belonged to the chief officer's
watch; the captain remained on deck when the watch was relieved,
and gave orders the same as usual; everything was attended to, and
his orders were punctually obeyed; everything went straightforward,
and there was no annoyance of any kind; all the men were quite
correct and obeyed orders; we stood along the coast till we fetched
the light up to the lee mizen rigging; the vessel was not labouring:
she came to her helm willingly; one man only was at the wheel until
we began to square yards, when two men were sent there; the lee
mizen rigging was on the port side of the ship; the Captain was on
the weather side of the deck; he had no night glass, but the second
mate had a case of what we call opera-glasses; when the light was
brought to bear upon the lee mizen rigging, all hands were piped up
by the boatswain; the hands turned up; the boatswain sung out for
"All hands to wear ship;" these were the words that were passed
along; the usual orders were given; when we came on deck, orders
were given to square away the yards; we got the orders to square
away; after a short time, the Captain gave orders to haul up the
foresail; it was then reefed; the ship then kept before the wind; the
light was clearly visible at times; when the words were given to
square the yards, the light had previously been seen; the vessel was
running in on a heavy sea; it was blowing very fresh in squalls, with
thick small rain; it was about eleven o'clock when the hands were
63. called up; there were two men on the forecastle with the third mate,
on the look-out for the land; the third mate was on the forecastle
with the two men, and the second mate was afterwards sent there
also; the captain sang out "Do you see anything of the North Head?"
and the mate said "No, I see nothing of it;" I was on the poop at this
time, standing by the braces; she had the light a bit on her port bow
when I saw it at this time; then the captain sang out to the man at
the wheel to keep his luff; the yards were about a point or so to
port; I heard these words; it was done; the course of the ship was
changed a small bit by this; shortly after this the second mate sang
out "Breakers ahead;" this was a few minutes afterwards; the
captain sung out to the man at the wheel to port his helm; we were
all at the braces: he told us to haul in the port braces, and brace the
yards sharp up; it was done quickly, without delay; there were
thirteen able seaman in each watch; there was no want of hands;
we were well manned, and we could see the light; it appeared to be
right over us; I heard no further orders given; a few minutes after
we hauled the yards round—about two minutes after—she went side
on to the rocks; she was trying to stretch out to the eastward, her
head lying along the land to the north; then we struck, and then the
screaming began, the passengers running about the deck screaming
for mercy; the captain was on the poop; he was cool and collected;
there was great confusion and uproar on the deck with the shrieks
of the passengers; with the first bump the three topmasts fell; the
first sea that came over us stove in the quarter-boats; none were
lowered; the mizen-mast went first, then the main-mast. The
foremast stood a long time; it was not more than five minutes after
she struck that she began to break up; I was on the poop at the
time; I caught hold of the mizen chains; when these gave way, I
made for the cabin, but the sea was coming down there enough to
smother one; I went below and got out of the cabin skylight to
leeward, and got up the side of the chain-plates of the fore-rigging;
this broke up at last, and I was thrown over still holding by the chain
plates, which held some four planks together, and I was thrown
upon the rocks in a heap of timber and rubbish; we made one signal
before we struck; we burnt a blue-light; the steward held it in a bit
64. of paper and burnt it all; he held it over the port side; this light was
visible for three or four minutes; he got orders from the captain to
do this before the vessel struck; no one was near me when I was
washed away; she kept breaking up from aft, and I kept getting
forward until at last I reached the chain plates of the fore-rigging; I
was washed away with planks and broken timber upon a shelf of
rock, but immediately on the sea receding I got up a bit higher out
of reach of the back current; we saw no vessel; we could not stand
off the land more than we were doing; I heard nothing said about
the captain not wishing to get further off the land for fear of being
driven to the northward; the captain could not stand off the land
more than he did; he did all that he could to keep off the land so far
as I can judge; I expected, when we squared away, that we were
going into the entrance of the harbour; I did not hear anybody say
this, but I thought from the squaring away that we were so; nobody
said that they saw the North Head; there was no opening that I
could see that would lead any one to believe that they were going
into port; I only saw the light; I was not frightened of anything; I
thought it was all right, and that we were going into harbour; this
was my idea until the second mate gave the alarm; the part that
struck first was the port bow; she struck the rocks below first, and
then bumped heavily over them; the vessel herself could not have
formed a breakwater for lowering boats to the leeward; besides, the
boats went with the first sea; the sea did not break right over her,
and even when the weather side broke up the lee side offered some
shelter; there is no truth in the report that the long boat was
launched, and that some of the passengers were put into it; I am
sure there had been no drinking aboard; we had a glass of grog at
12 o'clock; the men were all very steady; they were good men, and
many of them were working their passages out at a shilling a month,
intending to stop in the country; when I got ashore I could see
nothing, for the rain and darkness, and I could hear nothing but the
roaring of the surf; I saw nobody besides myself anywhere; the first
thing I saw in the morning was the dead bodies brought in by the
sea, and carried out by the under tow; the ship was completely
broken up, nothing remained but her fore yard; I could see no
65. persons; I was about ten yards above the sea, and the spray came
over me as the seas broke below; there was no hollow or anything;
underneath me, on the lower ledge, you could go a long way in
under the rock, but I liked to get higher up rather than to go in
under there; I had on a blue shirt, a singlet, and drawers; I hove
everything off—boots, trousers, and pea coat, when the first alarm
was given; we saw the light only a few minutes before the vessel
struck. The witness, who was further interrogated at some length by
the Coroner and the Foreman, gave his testimony in a very frank and
straightforward manner, and was followed by Captain Wiseman, of
the Grafton, steamer, at the conclusion of whose evidence the Court
adjourned for the purpose of allowing the jury to attend the funeral
procession.
When the inquest was subsequently resumed, Mr. A. Fletcher
(master of the Nora Creina Steamer, trading to Shoalhaven) gave his
evidence, followed by Messrs. Gorman and Raphael. In the course of
the melancholy enquiry, the Coroner took occasion to speak in high
terms of the zeal exhibited by Captain M'Lerie, Mr. North, Inspectors
Brown, Weale, and Cowell, and the police and citizens generally, in
the painful task of recovering the bodies of the sufferers, and in
preserving the property belonging to the wreck. The evidence having
been finished the Coroner addressed the Jury on the duty they owed
to the public, themselves, and the lamented captain of the wrecked
vessel, and urged upon them the necessity of acting justly and
conscientiously in the discharge of their important functions.
The Verdict.—After some deliberation, the following verdict was
returned:—"The jury find that the bodies viewed are those of some
of the passengers and crew of the ship Dunbar, out of London,
commanded by Captain Green, and bound to this port, and that the
ship Dunbar was wrecked outside the Sydney Heads, close to the
Gap, on the night of Thursday, the 20th August last, causing the
death of the said parties; there may have been an error of judgment
in the vessel being so close to the shore at night in such bad
weather, but the jury do not attach any blame to Captain Green or
66. his officers for the loss of the Dunbar. The jury consider it their duty
to put on record their opinion that the present Pilot arrangements
for this port are most inadequate, and desire to draw the attention
of the Government to the matter."
This concluded the proceedings, and the jury were discharged.
THE FUNERAL.
The procession moved from the dead-house at a little before five
o'clock. There were seven hearses, preceded by two officers of the
Mounted Police force. Each hearse was attended on its side by
mounted policemen, under the command of Captain M'Lerie. The
last hearse contained the remains of Captain Steine, a retired naval
officer, and the coffin was wrapped in the Union Jack, and was
followed by a company of sailors and two officers of her Majesty's
ship Herald and Iris.
There were four mourning coaches and a long string of carriages, of
which that of the Hon. Stuart A. Donaldson took the lead. One of the
mourners attending the funeral was Captain Macbeth, uncle to the
late Captain Green.
The band of the Artillery Companies formed a part of the procession,
and played the "Dead March from Saul" with fine effect. A company
of Artillery with two officers, between whom rode his Excellency the
Governor's Aide-de-Camp followed. The footpaths throughout the
streets of this city were literally walled with people. In proportion to
the number of inhabitants, never can we recollect a scene in which
the feeling of the people was so keenly and manifestly exhibited.
The shops were, with one or two exceptions, closed along the whole
line of road, and the streets thronged with silent and awe-struck
spectators, many of whom seemed much moved, while the knell,
67. sounding from some of the church bells, and flags hoisted half mast
high, added materially to the general gloom.
It was night before the funeral reached the Cemetery at O'Connell
Town, where the last sad obsequies were performed. The Rev. C. C.
Kemp read the service for the dead, in portions of which the large
concourse joined reverently: and, having taken a last look at the
grave, began slowly to disperse. It has been remarked that,
although the time had not been specially chosen for the ceremony,
the calmness of a dim moonlight seemed not unsuited to the close
of one of the most painful tragedies which has yet taken its place in
the annals of our Colony.
Opinions are of course somewhat divided as to the manner in which
(judging from Johnson's evidence and other circumstances) the ill-
fated Dunbar was commanded and manoeuvred on that dark and
memorable night; as to the amount of censure (if any) to be
attached to Captain Green, and as to numerous material facts, a
large number of persons exonerate the captain altogether; others,
although delivering themselves with moderation and delicacy, feel
compelled to consider that much lamented gentleman to have been
in some degree to blame for his orders and arrangements previous
to the catastrophe. This latter view of the matter has found a
forcible but temperate expression in the columns of the Sydney
Morning Herald, on the 25th instant, in striking and eloquent
language. The justice however of such a view has not been
generally recognised, either by the public, or the friends of Captain
Green. It is easy for landsmen and other self-constituted critics to
pass sentence now on that brave man, whose cause must be judged
in his absence—the inexorable King of Terrors having forbidden him
to enter upon his defence, or even to hear his accusers.
Nevertheless, it should be borne in mind that the land at Botany,
seen at about 7 p.m. on Thursday night, was made by mere dead
reckoning, the commander not having (as it would appear) seen the
sun for several days; the time when it was so made being already
night, the weather dark, tempestuous, and rainy. What if the land
68. thus seen through the murky atmosphere were but so imperfectly
observed that Captain Green might well be deceived as to its real
distance, and reasonably suppose himself to be a mile or two nearer
to, or farther off from it than he actually was? Would not that very
probable circumstance interfere with the course to be pursued, and
justify (nay even demand) measures, which have under adverse
circumstances, been attended with such unhappy results? Dead
upon a lee shore at an uncertain distance, and with a most uncertain
light, the wind and sea both setting in fearfully towards the land, it
may have been an awful fact, known only to one brave heart who
fought it out to the last, that under all these conjunctures the sailing
qualities of the Dunbar would not permit her to keep out to sea that
night. Hour after hour, minute after minute, notwithstanding all
careful steering she made a lee-way, which, no change of wind
occurring, must at last have thrown her bodily somewhere upon the
coast. This lee-way could not be securely calculated upon, even by
him who knew the Dunbar so well, because his first idea of distance
when he sighted Botany was, to say the least, uncertain, if not
untrue. Captain Green shaped his course for the North Head (it was
of that he spoke at the last), but he only fetched the fatal rocks at
the Gap. It seems doubtful to many if he could have done anything
more than what he did do, and thus his duty to the utmost
performed, Green met his death with calmness, as a brave man
should. The only particular pang that might then have shot through
him would be this—that he would be more or less condemned
unheard, carrying with him his own strong, unanswerable defence.
God alone knows all he had to struggle against, and to weigh in his
mind that night.
One good result of this will probably be that we shall at length have
proper arrangements for lighting the rocky portal of our harbour, and
for something less feeble and inefficient than our present Pilot
system; crying defects for which it is ungenerous and unjust to
blame a Government recently formed, and still struggling against a
powerful Opposition. These two discreditable items are legacies for
which, others are virtually, although no longer legally, responsible.
69. The following practical remarks from a well known Colonial author
on these matters appeared in the Sydney Morning Herald of the 26th
instant, and seem to merit particular attention. "I begin," says the
writer, "by denying the assertion often made, that Sydney Heads are
safe to enter in any weather; still, let it be understood that I speak
of nightwork only. With the wind off the land, smooth water, moon,
stars, and all other assistances of that kind, it may be well enough,
but even then it is fit to shake the nerves of a man coming off a long
voyage, when he gets fairly in the entrance—for the light is then lost
—and sees nothing but the towers of black rock in one unbroken line
frowning defiance at him. If such be the coast when a weather-
shore, what must it be when a lee one. The harbour is well enough
to make, no one can contradict that, but with a strong wind blowing
on the land—the ship scudding, and thick sudden showers of rain,
the characteristic of our east winds, making the darkness
impenetrable; there perhaps is not another port in the world more
terribly confusing to a seaman to enter than the loudly-lauded one of
Sydney. In most other ports, or estuaries, many mistakes may be
made, and yet with little or no loss of life; here there only can be
one made, but that is the final and fatal one. An error of a little half-
mile, as in the case of the poor Dunbar, and all is lost; a single look
from the most inexperienced eye reads on that rampart of cliffs
nothing but rude and mangled death. If I have said anything to
shake the general belief that Sydney is such a safe port to enter, let
us now see what may be done to make it safer, and to prevent, if
possible, by human means, the recurrence of two such shipwrecks
as have slain their hundreds before our eyes. [Alluding to the wreck
of the Edward Lombe in 1834.] Although with only an interval of
some twenty-three years between them, methinks we have had time
to think over the matter, and now to move ourselves.
Prevention the first.—More lights. Had I—or any other, a
twelvemonth ago, written as much, we should have been "pooh
poohed" for our pains; had we been able to advance the matter in
the House of Parliament, we should have been told by the
Opposition, or the Government, whichever had the economical
70. perplexity at the time, that "the country could not afford any more
lights." But "the country" can't, and the people won't afford any
more losses like the last one, and therefore now it can be both
boldly said and written, that something must and shall be done in
the matter.
As to the situation of any more lights for the entrance to Port
Jackson, no doubt there will be many opinions. The North Head has
been mentioned as a site for this leading light, but my own
convictions, borne out by the judgment of others of great
experience, goes against the North Head only being lighted; and if
only one light should be added, that there is another situation
preferable. Because every seaman knows that a light on a high cliff
in thick rain squalls, which is the weather we have here to dread, is
not so easily seen as a light placed a moderate distance above the
water's edge. Therefore, if one light only should be added, that light
should be placed where the turning point of the entrance takes place
—in this case the low point of the South Reef—a red light visible
eight miles. And perhaps it would not be at all amiss to say, in the
Sailing Directions for the Port of Sydney (a copy of which, by the
way, I have not seen for a long time in places of resort for seamen,
being very likely out of print), that unless such leading light is seen,
no sailing vessel with an east wind at night (coasters excluded)
should attempt the entrance without a pilot, as long as she can keep
to sea.—Having stumbled upon the word pilot, we may write—
Prevention second.—A more effective system of pilotage at Port
Jackson Heads. Let me be understood when I say effective system
of pilotage, because I do not for a moment throw blame or slur upon
the pilots now at the Heads, but I think it disgraceful to the
Government of New South Wales that such a paltry system should
be kept alive when I see the way they manage things in Melbourne.
It strikes me very forcibly that a pilot-cutter—one of those crafts that
can keep the sea in any weather, would be very beneficial in
preventing any more wrecks like that of the Dunbar. And I venture it
as my opinion, that had such a vessel, with six, or any other number
71. of good men and true in her, been cruising off the Sydney Heads, we
should not now have to lament the loss of the ship Dunbar, and all
hands, save one, on the night of August 20th, 1857. That cutter
would have been cruising on such a night with Sydney lights bearing
from N.N.W. to W.N.W., or thereabouts, distant from 10 to 15 miles,
she would in all probability have put a pilot on board the Dunbar (if
Johnson's account is correct) with daylight, and before the gale
came on. Had the cutter not been able to board the ship, the latter
would have been ordered to answer the flash-light which all pilot
vessels burn every half-hour, and there is little doubt that men
intimately acquainted with coasting work, which long-voyage ship-
masters cannot possibly be, would have seconded the first order by
an urgent request to make more sail and keep to sea, if possible; or,
had the pilots deemed the entrance at all practicable, yet without
being able to board the ship, the latter would have been directed to
follow in the wake of the cutter, as is continually done on the coast
of England.
D. P."
More bodies have been discovered in the North Harbour, since the
compilation of the foregoing narrative, but they have not, it is
believed, been yet identified. The matter of wreck was mentioned in
the House of Assembly, on Tuesday evening last. A debate thereon
seemed at one time likely to supervene, but the discussion was very
properly stopped by the Speaker as irregular.
Our readers may be interested to learn that poor Johnson has a
trade (that of a rough carpenter) and does not purpose for the
present, at all events, to return to the dangers of a seafaring life. We
beg to suggest that a shilling subscription be set on foot in his
behalf, so as to buy him tools and clothing, and thus set him up in
business. We feel confident that if the subscription be made, thus
low, hundreds will willingly contribute. The Right Worshipful the
72. Mayor, Captain McLerie, and the Police Magistrates, who have
already taken so warm an interest in the sad event would doubtless
not refuse their aid and sanction to what is now proposed.
A short description of the locality where the late melancholy
catastrophe occurred may be interesting to those not acquainted
with it. From the outer South Head (near which the lighthouse
stands) to the South Reef, at the entrance of Port Jackson, the
distance is about a mile and a half. It is between these two points
that the catastrophe occurred. The coast is very high and steep,
and, indeed, may be said to be inaccessible. Next to the South Reef
is a small bight, commonly known as the Gap, and here are large
table rocks nearly level with the surface of the water, and as smooth
as if cut by the chisel of the mason. Here, more perhaps than
anywhere else, the breakers roll in with excessive violence.
The Gap is a very short distance from the flagstaff at South Head,
near which place it is supposed the Dunbar struck. In the fearful sea
that was running on Thursday night it is a miracle that a single soul
has been saved. Here in fact, must have been the place where the
ship went ashore, as on the morning of the wreck no traces of the
ship could be seen further south. When, however, the ebb tide
made, the wreck would of course be sent towards the entrance of
the port, and the easterly wind and sea, assisted by the subsequent
flood tide, would drift the bodies and floating masses into Middle
Harbour, where, indeed, the greater portion of the debris and a
number of bodies were found to be deposited.
James Fryer, Machine and General Printing Office, 322, George-
street, Sydney.
74. *** END OF THE PROJECT GUTENBERG EBOOK A NARRATIVE OF
THE MELANCHOLY WRECK OF THE "DUNBAR," MERCHANT SHIP, ON
THE SOUTH HEAD OF PORT JACKSON, AUGUST 20TH, 1875 ***
Updated editions will replace the previous one—the old editions
will be renamed.
Creating the works from print editions not protected by U.S.
copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.
START: FULL LICENSE
76. PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK
To protect the Project Gutenberg™ mission of promoting the
free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.
Section 1. General Terms of Use and
Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.
1.B. “Project Gutenberg” is a registered trademark. It may only
be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
77. 1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E. Unless you have removed all references to Project
Gutenberg:
1.E.1. The following sentence, with active links to, or other
immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
78. Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and
with almost no restrictions whatsoever. You may copy it,
give it away or re-use it under the terms of the Project
Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country
where you are located before using this eBook.
1.E.2. If an individual Project Gutenberg™ electronic work is
derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.
1.E.3. If an individual Project Gutenberg™ electronic work is
posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.
1.E.4. Do not unlink or detach or remove the full Project
Gutenberg™ License terms from this work, or any files
79. containing a part of this work or any other work associated with
Project Gutenberg™.
1.E.5. Do not copy, display, perform, distribute or redistribute
this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
1.E.7. Do not charge a fee for access to, viewing, displaying,
performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.
1.E.8. You may charge a reasonable fee for copies of or
providing access to or distributing Project Gutenberg™
electronic works provided that:
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
80. Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com