0% found this document useful (0 votes)
28 views

Android Cookbook 2nd [early release] Edition Ian F. Darwin download

The document is a promotional overview for the 'Android Cookbook 2nd Edition' by Ian F. Darwin, which provides resources for Android app development. It includes links to download the ebook and other related titles by the same author. The content covers various aspects of Android development, including application architecture, design, testing, and user interface guidelines.

Uploaded by

cdkqinami
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Android Cookbook 2nd [early release] Edition Ian F. Darwin download

The document is a promotional overview for the 'Android Cookbook 2nd Edition' by Ian F. Darwin, which provides resources for Android app development. It includes links to download the ebook and other related titles by the same author. The content covers various aspects of Android development, including application architecture, design, testing, and user interface guidelines.

Uploaded by

cdkqinami
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Android Cookbook 2nd [early release] Edition Ian

F. Darwin pdf download

https://ebookname.com/product/android-cookbook-2nd-early-release-
edition-ian-f-darwin/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Java Cookbook 4th Edition Ian F. Darwin

https://ebookname.com/product/java-cookbook-4th-edition-ian-f-
darwin/

Java Cookbook 1st Edition Ian F. Darwin

https://ebookname.com/product/java-cookbook-1st-edition-ian-f-
darwin/

Android Application Development Cookbook Second Edition


Rick Boyer

https://ebookname.com/product/android-application-development-
cookbook-second-edition-rick-boyer/

The twentieth century world and beyond an international


history since 1900 4th ed 4th ed. Edition Keylor

https://ebookname.com/product/the-twentieth-century-world-and-
beyond-an-international-history-since-1900-4th-ed-4th-ed-edition-
keylor/
The Aesthetics of Equity Notes on Race Space
Architecture and Music 1st Edition Craig L. Wilkins

https://ebookname.com/product/the-aesthetics-of-equity-notes-on-
race-space-architecture-and-music-1st-edition-craig-l-wilkins/

Autism Your Questions Answered 1st Edition Romeo


Vitelli

https://ebookname.com/product/autism-your-questions-answered-1st-
edition-romeo-vitelli/

Developing Teaching and Learning in Higher Education


1st Edition Gill Nicholls

https://ebookname.com/product/developing-teaching-and-learning-
in-higher-education-1st-edition-gill-nicholls/

Crisis Cause Containment and Cure Second Edition Thomas


F. F. Huertas

https://ebookname.com/product/crisis-cause-containment-and-cure-
second-edition-thomas-f-f-huertas/

BT Fast Tank The Red Army s Cavalry Tank 1931 45 Steven


J. Zaloga

https://ebookname.com/product/bt-fast-tank-the-red-army-s-
cavalry-tank-1931-45-steven-j-zaloga/
Physics and Engineering of Radiation Detection Second
Edition Syed Naeem Ahmed

https://ebookname.com/product/physics-and-engineering-of-
radiation-detection-second-edition-syed-naeem-ahmed/
SECOND EDITION

Android Cookbook

Ian Darwin
Android Cookbook
by Ian F. Darwin
Copyright © 2016 O’Reilly Media, Inc.. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc. , 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles ( http://safaribooksonline.com ). For more information, contact our corporate/
institutional sales department: 800-998-9938 or corporate@oreilly.com .

Editors: Dawn Schanafelt and Meghan Blanchette Indexer: FILL IN INDEXER


Production Editor: FILL IN PRODUCTION EDI‐ Interior Designer: David Futato
TOR Cover Designer: Karen Montgomery
Copyeditor: FILL IN COPYEDITOR Illustrator: Rebecca Demarest
Proofreader: FILL IN PROOFREADER

January -4712: Second Edition

Revision History for the Second Edition


2016-10-11: First Early Release

See http://oreilly.com/catalog/errata.csp?isbn=9781449374457 for release details.

The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Android Cookbook, the cover image,
and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the author(s) have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and the author(s) disclaim all responsibil‐
ity for errors or omissions, including without limitation responsibility for damages resulting from the use
of or reliance on this work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is subject to open source
licenses or the intellectual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.

978-1-449-37445-7
[FILL IN]
Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

1. Getting Started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.1 Understanding the Android Application Architecture 17
1.2 Understanding the Android Activity Life Cycle 19
1.3 Learning About Android Releases 21
1.4 Learning the Java Language 23
1.5 Creating a “Hello, World” Application from the Command Line 24
1.6 Creating a “Hello, World” App with Apache Maven 29
1.7 Choosing an IDE for Android Development 31
1.8 Setting Up Android Studio 34
1.9 Creating a “Hello, World” App using Android Studio 37
1.10 Converting an Eclipse ADT Project to Android Studio 44
1.11 Preserving History while Converting from Eclipse to Android Studio 48
1.12 Setting Up Eclipse with AndMore (Replacing ADT) 50
1.13 Creating a “Hello, World” Application using Eclipse 59
1.14 Installing the Eclipse Marketplace Client in your Eclipse 66
1.15 Upgrading a Project from Eclipse ADT to Eclipse AndMore 71
1.16 Using Java 8 Features in Android Studio 2 74
1.17 Controlling Emulators/Devices Using Command-Line ADB 76
1.18 Sharing Java Classes from Another Eclipse Project 80
1.19 Referencing Libraries to Implement External Functionality 83
1.20 Using New Features on Old Devices via the Compatibility Libraries 88
1.21 Using SDK Samples to Help Avoid Head Scratching 90
1.22 Taking a Screenshot/Video from the Emulator/Android Device 93
1.23 Program: A Simple CountDownTimer Example 99
1.24 Program: Tipster, a Tip Calculator for the Android OS 102

iii
2. Designing a Successful Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
2.1 Exception Handling 124
2.2 Requesting Android Permissions at Run Time 128
2.3 Accessing Android’s Application Object as a “Singleton” 130
2.4 Keeping Data When the User Rotates the Device 132
2.5 Monitoring the Battery Level of an Android Device 135
2.6 Creating Splash Screens in Android 136
2.7 Designing a Conference/Camp/Hackathon/Institution App 141
2.8 Using Google Analytics in an Android Application 142
2.9 Setting First-Run Preferences 145
2.10 Formatting the Time and Date for Display 147
2.11 Simplifying Date/Time Calculations with the Java 8 java.time API 149
2.12 Controlling Input with KeyListeners 151
2.13 Backing Up Android Application Data 155
2.14 Using Hints Instead of Tool Tips 161

3. Application Testing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165


3.1 Setting Up an Android Virtual Device (AVD) for App Testing 166
3.2 Testing on a Huge Range of Devices with Cloud-based Testing 175
3.3 Testing with Eclipse and JUnit 176
3.4 Testing with Android Studio and JUnit 180
3.5 Testing with Robolectric and JUnit 4 186
3.6 Testing with ATSL, Espresso and JUnit 4 188
3.7 Troubleshooting Application Crashes 193
3.8 Debugging Using Log.d and LogCat 196
3.9 Getting Bug Reports Automatically with Crash Reporting 198
3.10 Using a Local Runtime Application Log for Analysis of Field Errors or
Situations 201
3.11 Reproducing Activity Life-Cycle Scenarios for Testing 205
3.12 Keeping Your App Snappy with StrictMode 211
3.13 Static Code Testing with Android Lint 212
3.14 Dynamic Testing with the Monkey Program 214
3.15 Sending Text Messages and Placing Calls Between AVDs 216

4. Inter-/Intra-Process Communication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219


4.1 Opening a Web Page, Phone Number, or Anything Else with an Intent 219
4.2 Emailing Text from a View 222
4.3 Sending an Email with Attachments 225
4.4 Pushing String Values Using Intent.putExtra() 226
4.5 Retrieving Data from a Sub-Activity Back to Your Main Activity 227
4.6 Keeping a Background Service Running While Other Apps Are on Display 230
4.7 Sending/Receiving a Broadcast Message 232

iv | Table of Contents
4.8 Starting a Service After Device Reboot 233
4.9 Creating a Responsive Application Using Threads 234
4.10 Using AsyncTask to Do Background Processing 236
4.11 Sending Messages Between Threads Using an Activity Thread Queue and
Handler 244
4.12 Creating an Android Epoch HTML/JavaScript Calendar 245

5. Graphics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
5.1 Using a Custom Font 253
5.2 Drawing a Spinning Cube with OpenGL ES 256
5.3 Adding Controls to the OpenGL Spinning Cube 260
5.4 Freehand Drawing Smooth Curves 263
5.5 Taking a Picture Using an Intent 268
5.6 Taking a Picture Using android.media.Camera 270
5.7 Scanning a Barcode or QR Code with the Google ZXing Barcode Scanner 274
5.8 Using AndroidPlot to Display Charts and Graphs 277
5.9 Using Inkscape to Create an Android Launcher Icon 280
5.10 Creating Easy Launcher Icons from OpenClipArt.org Using Paint.NET 287
5.11 Using Nine Patch Files 294
5.12 Creating HTML5 Charts with Android RGraph 298
5.13 Adding a Simple Raster Animation 302
5.14 Using Pinch to Zoom 306

6. Graphical User Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311


6.1 Understanding and Following User Interface Guidelines 312
6.2 Looking Good with Material Design 313
6.3 Choosing a Layout Manager (ViewGroup) and Arranging Components 320
6.4 Handling Configuration Changes by Decoupling the View from the Model 321
6.5 Controlling the Action Bar 325
6.6 Adding a Share Action to your action bar 329
6.7 Building Modern UIs with the Fragment API 339
6.8 Creating a Button and Its Click Event Listener 344
6.9 Enhancing UI Design Using Image Buttons 345
6.10 Using FloatingActionButton 347
6.11 Wiring Up an Event Listener in Five Different Ways 350
6.12 Using CheckBoxes and RadioButtons 355
6.13 Using Card Widgets 359
6.14 Offering a Drop-Down Chooser via the Spinner Class 363
6.15 Handling Long-Press/Long-Click Events 366
6.16 Displaying Text Fields with TextView and EditText 367
6.17 Constraining EditText Values with Attributes and the TextWatcher
Interface 368

Table of Contents | v
6.18 Implementing AutoCompleteTextView 371
6.19 Feeding AutoCompleteTextView Using an SQLite Database Query 373
6.20 Turning Edit Fields into Password Fields 375
6.21 Changing the Enter Key to “Next” on the Soft Keyboard 376
6.22 Processing Key-Press Events in an Activity 379
6.23 Let Them See Stars: Using RatingBar 380
6.24 Making a View Shake 384
6.25 Providing Haptic Feedback 386
6.26 Navigating Different Activities Within a TabView 389
6.27 Formatting Numbers 391
6.28 Formatting with Correct Plurals 395
6.29 Creating a Loading Screen That Will Appear Between Two Activities 398
6.30 Adding a Border with Rounded Corners to a Layout 400
6.31 Detecting Gestures in Android 402
6.32 Creating a Simple App Widget 409

vi | Table of Contents
To Dennis M. Ritchie (1941–2011), language pioneer and co-inventor of Unix, who
showed us all where the braces go, reminded us to keep it simple, and gave us so much
more…
Preface

===
Ian Darwin
Android is “the open source revolution” applied to cellular telephony and mobile
computing. At least, part of the revolution. There have been many other attempts to
provide open source cell phones, most of them largely defunct, ranging from the
Openmoko FreeRunner to QT Embedded, Moblin, LiMo, Debian Mobile, Maemo,
FireFox OS, Ubuntu Mobile to the open sourced Symbian OS and the now-defunct
HP WebOS. Let’s not forget the established closed source stalwart Apple’s iOS, and
the two minor players (by market share), Microsoft Windows Mobile and the
recently-abandoned BlackBerry OS 10 (both of these have developer toolkits, but
their OS is not available as open source and often has other “click-wrap” restrictions).
Amongst all these offerings, two stand out as major players. Android is definitely
here to stay! This book is here to help the Android developer community share the
knowledge that will help make better apps. Those who contribute knowledge here are
helping to make Android development easier for those who come after.

About Android
Android is a mobile technology platform that provides cell phones, tablets, and other
handheld and mobile devices (even netbooks) with the power and portability of the
Linux operating system and the reliability and portability of a standard high-level
language and API and a vast ecosystem of useful applications. Android apps are
mostly written in the Java language, using tools such as Eclipse and Android Studio,
compiled against the Android API, and translated into bytecode for an Android-
specific VM.
Android is thus related by OS family to other Linux-based cell phone projects.
Android is also related by programming language to BlackBerry’s older Java ME
phones, and to Java and the wider realm of Java Enterprise applications. Not to men‐

ix
tion that all current Blackberry devices can run Android applications, and in fact
Blackberry’s newest devices only run Android.
It’s now generally believed that Android has almost three-quarters of the world
smartphone market, although it has not nearly displaced Apple’s iPad in the tablet
market. Sales figures change all the time, but it is clear that Android is, and will
remain, one of the dominant players in the mobile space.

Who This Book Is By


This book was written by several dozen Android developers from the Android com‐
munity at large. Development occurred in the open, on the website http://androidcook
book.com/, which I built (using Java of course) to allow people to contribute, view,
review, and comment on the recipes that would make up this book. A complete list
can be found in “Acknowledgments” on page xv. I am deeply grateful to all the con‐
tributors, who have helped moved this book from a dream to the reality that you have
in your hands (or on-screen if you are reading the ebook format). Thank you all!

Who This Book Is For


This book focusses on building Android applications using Java, the native language
of Android applications. It is of course possible to package up a web application as a
mobile app (see ???), but you will never get the all-important 100%-correct user expe‐
rience with all the current features of Android that way.
So. Java. We assume you know the basics of the Java language. If not, see Recipe 1.4.
We also assume you know the basics of the Java Standard Edition API (since this
forms the basis of Android’s runtime libraries) as well as the basics of Android. The
terms activity, intent, service, and content provider, while not necessarily being what
you dream about at night, should at least be familiar to you. But if not, we’ve got you
covered: see Recipe 1.2.
This book differs from the Android Samples assocated with the Android SDK in that
it tries to focus more on how a given piece of technology works, rather than by giving
you (as the Samples do) a complete, working, example that has both been simplified
(to use very simple data) but complicated by adding in several “neat” features that are
irrelevant to the problem at hand.

What’s in This Book?


Chapter 1 takes you through the steps of setting up the Android development envi‐
ronment and building several simple applications of the well-known “Hello, World”
type pioneered by Brian Kernighan.

x | Preface
Chapter 2 covers some of the differences in mobile computing that will hit developers
coming from desktop and enterprise software environments, and talks about how
mobile design (in particular, Android design) differs from those other environments.
Testing is often an afterthought for some developers, so we discuss this early on, in
Chapter 3. Not so that you’ll skip it, but so that you’ll read and heed. We talk about
unit testing individual components as well as testing out your entire application in a
well-controlled way.
Android provides a variety of mechanisms for communicating within an application
and across applications. In Chapter 4 we discuss intents and broadcast receivers, serv‐
ices, AsyncTasks, and handlers.
Chapter 5 covers a range of topics related to graphics, including use of the graphical
drawing and compositing facilities in Android as well as using desktop tools to
develop graphical images, textures, icons, and so on that will be incorporated into
your finished application.
Every mobile app needs a GUI, so Chapter 6 covers the main ins and outs of GUI
development for Android. Examples are given both in XML and, in a few cases, in
Java-coded GUI development.
??? covers all the pop-up mechanisms—menus, dialogs, and toasts—and one that
doesn’t pop up but is also for interaction outside your application’s window, Android’s
notification mechanism.
Lists of items are very common in mobile applications on all platforms. ??? focuses on
the “list” components in Android, the ListView and its newer replacement the
RecyclerView.
Android is rich in multimedia capabilities. ??? shows how to use the most important
of these.
??? shows how to save data into files, databases, and so on. And how to retrieve it
later, of course. Another communication mechanism is about allowing controlled
access to data that is usually in an SQL database. This chapter also shows you how to
make application data available to other applications through something as simple
but ubiquitous (in Android) as the URL, and how to use various cloud-based services
to store data.
Android started out as an operating system for mobile telephones. ??? shows how to
control and react to the telephone device that is in most mobile devices nowadays.
Mobile devices are, for the most part, always-on and always-connected. This has a
major impact on how people use them and think about them. ??? shows the coding
for traditional networked applications. This is followed by ???, and ???.

Preface | xi
The now-ubiquitous Global Positioning System has also had a major impact on how
mobile applications work. ??? discusses how to find your location, how to get map
data from Google and OpenStreetMap, and how applications can be location-aware
in ways that are just now being explored.
??? talks about the sensors built into most Android devices and how to use them.
??? talks about the low-energy very-local area networking that Bluetooth enables,
going beyond connecting your Bluetooth headset to your phone.
Android devices are perhaps unique in how much control they give the developer.
Some of these angles are explored in ???. Since Android is Linux-based, a few of the
recipes in this chapter deal with traditional Unix/Linux commands and facilities.
In ???, we explore the use of other programming languages to write all or part of your
Android application. Examples include C, Perl, Python, Lisp, and other languages.
While this edition of this book is in English, and English remains the number-one
technical language worldwide, it is far from the only one. Most end users would
rather have an application that has its text in their language and its icons in a form
that is culturally correct for them. ??? goes over the issues of language and culture and
how they relate to Android.
Most Android developers hope other people will use their applications. But this won’t
happen if users can’t find the applications. ??? shows how to prepare your application
for distribution via the Android Market, and to use that as well as other markets to
get your application out to the people who will use it.

Conventions Used in This Book


The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program ele‐
ments such as variable or function names, databases, data types, environment
variables, statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.

xii | Preface
This icon signifies a tip, suggestion, or general note.

This icon indicates a warning or caution.

And here is our first caution: the term “I” used in a given recipe
reflects the opinions or experience of that recipe’s contributor, not
necessarily of the book’s editor.

Getting and Using the Code Examples


The code examples in this book vary from a few lines pasted from a complete applica‐
tion, through to fully working apps. For those at the “few lines” end of the spectrum,
you should not expect to be able to compile them from what we provide; these are
intended to be merged into your application. All the examples that we have code for
and that are compilable have been merged into a single GitHub repository, which is
the recommended way of getting the source code and keeping it up to date. This reposi‐
tory can be accessed at https://github.com/IanDarwin/Android-Cookbook-Examples.
Each directory in the repo contains one example program’s project. As you will see if
you visit this page, GitHub allows you to check out the source repository using the
git clone command. As well, the web page offers the option to download the entire
repository as a single (large) ZIP file as well as to browse portions of the repository in
a web browser. Using git will allow you to receive corrections and updates, but the
ZIP will download more quickly.
Contributors of each recipe also have the option to provide a download URL for their
source code, hosted on some other public repository. These are listed both as a hyper‐
link for eBook users and as a QR-format barcode for downloading from the printed
edition. These URLs are included at the end of each recipe. In each case the archive
file is expected to contain a complete Eclipse project. We have no control over these
other repositories, so if one of them is incomplete, or stops working, please refer to
the GitHub repository instead.
This book is here to help you get your job done. In general, you may use the code in
this book in your programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the code. For example,
writing a program that uses several chunks of code from this book does not require

Preface | xiii
permission. Selling or distributing a CD-ROM of examples from O’Reilly books does
require permission. Answering a question by citing this book and quoting example
code does not require permission. Incorporating a significant amount of example
code from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the
title, author, publisher, and ISBN. For example: "Android Cookbook, edited by Ian F.
Darwin (O’Reilly). Copyright 2016 O’Reilly Media, Inc., 978-1-449-37443-3.”
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us at permissions@oreilly.com.

Safari® Books Online


Safari Books Online is an on-demand digital library that lets you
easily search over 7,500 technology and creative reference books
and videos to find the answers you need quickly.

With a subscription, you can read any page and watch any video from our library
online. Read books on your cell phone and mobile devices. Access new titles before
they are available for print, and get exclusive access to manuscripts in development
and post feedback for the authors. Copy and paste code samples, organize your favor‐
ites, download chapters, bookmark key sections, create notes, print out pages, and
benefit from tons of other time-saving features.
O’Reilly Media has uploaded this book to the Safari Books Online service. To have
full digital access to this book and others on similar topics from O’Reilly and other
publishers, sign up for free at http://my.safaribooksonline.com.

How to Contact Us
Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.


1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)

xiv | Preface
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at:

http://shop.oreilly.com/product/0636920038092.do

To comment or ask technical questions about this book, send email to:

bookquestions@oreilly.com

For more information about our books, courses, conferences, and news, see our web‐
site at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments
I would like to thank the dozens of people from the Android community at large who
contributed so many of the recipes in the first edition of this book: Amir Alagic, Jim
Blackler, Luis Vitorio Cargnini, Rupesh Chavan, Adrian Cowham, Nidhin Jose Davis,
Wagied Davids, David Dawes, Enrique Diaz, Marco Dinacci, Claudio Esperanca, Kur‐
osh Fallahzadeh, Daniel Fowler, Jonathan Fuerth, Sunit Katkar, Roger Kind Kristian‐
sen, Vladimir Kroz, Alex Leffelman, Ulysses Levy, Thomas Manthey, Emaad Man‐
zoor, Keith Mendoza, Roberto Calvo Palomino, Federico Paolinelli, Johan Pelgrim,
Catarina Reis, Mike Rowehl, Pratik Rupwal, Oscar Salguero, Ashwini Shahapurkar,
Shraddha Shravagi, Rachee Singh, Saketkumar Srivastav, Corey Sunwold, Kailuo
Wang, and Colin Wilcox.
Thanks to Mike Way who contributed the Permissions recipe Recipe 2.2 for the Sec‐
ond Edition, and Daniel Fowler for updating several of his recipes to coincide with
the Second Edition.
I must also mention the many people at O’Reilly who have helped shape this book,
including my editors Mike Loukides, Courtney Nash, Meghan Blanchette and Dawn
Schanafelt; Adam Witwer and Sarah Schneider in production; production editor Ter‐
esa Elsey, who shepherded the whole production process; external copy editor Audrey
Doyle, who painstakingly read every word and phrase; Stacie Arellano, who proof‐
read it all again; Lucie Haskins, who added index terms to all those recipes; designers
Karen Montgomery and David Futato; illustrators Robert Romano and Rebecca
Demarest; and anyone whom I’ve neglected to mention—you know who you are!
My late son Andrej Darwin helped with some administrative tasks late in the recipe
editing phase of the first edition. Thanks to all my family for their support.

Preface | xv
Finally, a note of thanks to my two technical reviewers, Greg Ostravich and Zettie
Chinfong, without whom there would be many more errors and omissions than the
ones that doubtless remain. Rick Isaacs made another pass and tested many recipes.
Thanks also to the many people who pointed out minor errors and omissions in the
first printing of the book, especially Anto Jurkovic and Joseph C. Eddy; most of these
have been corrected at this time. The errors which surely remain are my own.
To all of the above, thank you!

Content Updates
Second Edition, June 2016
Major revision for Android Nougat (7.x). As befits a major revision, there are numer‐
ous new recipes to cover all the new (and a few replaced) APIs over the past several
releases of Android.

xvi | Preface
CHAPTER 1
Getting Started

The famous “Hello, World” pattern came about when Kernighan and Plaugher
wanted to write a “recipe” on how to get started in any new programming language
and environment. Their idea was that, if you could get a computer program to print
out “Hello World”, then you had mastered how to use the system in general, how to
create/edit a program’s source code, compile/translate/process it into a runnable pro‐
gram as needed, and run it. And once you’d done that you could, with elaboration,
make the computer do anything! This chapter is affectionately dedicated to these fine
gentlemen, and to everyone who has ever struggled to get started in a new program‐
ming paradigm.
This chapter is a smorgasbord of “how to get started” recipes. We show you how to
create and build an Android app using almost no tooling, using Apache Maven, using
Eclipse, using Gradle, and using Android Studio. Nobody will regularly use all these
techniques, but we chose to cover them all because some readers will like each way of
doing things. Feel free to pick and choose, and try different ways of working on your
application!

1.1 Understanding the Android Application Architecture


Ian Darwin

Problem
An Android application consists of many “moving parts” whose natures and interac‐
tions need to be understood in order to develop effectively.

17
Discussion
An Android application consists of one or more of the following components, written
as Java classes:

• An Activity comprises the visual components (”Views”) for one screen as well as
the code that can respond to user events on that screen. Almost every application
has at least one Activity class.
• A Service is a component that has no user interface, and can run for a longer
period of time than an Activity. Two main uses for Services are long-running
tasks (such as a music player), and running medium-length tasks without tying
up the user-interface thread.
• Broadcast Receivers are less common, and are used to respond to system-wide
events such as the network losing or regaining connectivity, the battery running
low, the system rebooting, and so on.
• Content Providers are also relatively rare, and are used when one application
needs to share its data with other applications; they can also be used with Sync
Adapters (see below);
• Sync Adapters synchronize data with cloud services; the best-known examples
are the Contacts and Calendar on the device, which can easily be synchronized to
your Google account.

Your code does not create these objects using the new operator, as in conventional
Java, but requests their invocation using an Intent, an object that specifies your
intention to have something done. Intents can start activities within your application
(by class name), start activities in other applications (by specifying content type and
other information), start services, and request other operations. The interactions
among these components are outlined in Figure 1-1.

18 | Chapter 1: Getting Started


Figure 1-1. Android Application Components

Of these, the Activity is the most basic component, and the place you need to start
when learning to develop Android applications.

1.2 Understanding the Android Activity Life Cycle


Ian Darwin

Problem
Android apps do not have a “main” method; you need to understand how they get
started and how they stop or get stopped.

Solution
The class android.app.Activity provides a number of well-defined life-cycle meth‐
ods that are called when an application is started, suspended, restarted, and so on, as
well as a method you can call to mark an activity as finished.

1.2 Understanding the Android Activity Life Cycle | 19


Discussion
Your Android application runs in its own Unix process, so in general it cannot
directly affect any other running application. The Android Runtime interfaces with
the operating system to call you when your application starts, when the user switches
to another application, and so on. There is a well-defined life cycle for Android appli‐
cations.
An Android app can be in one of three states:

• Active, in which the app is visible to the user and is running


• Paused, in which the app is partly obscured and has lost the input focus, e.g.,
when a Dialog is in front of your Activity.
• Stopped, in which the app is completely hidden from view

Your app will be transitioned among these states by Android calling the following
methods on the current activity at the appropriate time:
void onCreate(Bundle savedInstanceState)
void onStart()
void onResume()
void onRestart()
void onPause()
void onStop()
void onDestroy()
You can see the state diagram for this life cycle in Figure 1-2.

Figure 1-2. Android life-cycle states

20 | Chapter 1: Getting Started


For an application’s first activity, onCreate() is how you know that the application
has been started. This is where you normally do constructor-like work such as setting
up the “main window” with setContentView(), adding listeners to buttons to do
work (including starting additional activities), and so on. This is the one method that
even the simplest Android app needs.
Note that most applications today base their UI on Fragments. A Fragment is a frag‐
ment of the UI for an Activity. For example, in the early days of Android a typical list-
detail application would use two Activities, one for the list and one for the detail. This
is still allowed, of course, but has the drawback that, on a tablet, or a large screen
phone in landscape mode, it isn’t possible to have both views side-by-side. An Activ‐
ity can be divided into multiple Fragments (see Recipe 6.7), which solves this prob‐
lem. A Fragment can only exist inside an Activity. The Fragment life cycle is similar
to that of the Activity cycle, but has a few additional methods.
You can see the invocations of the various life cycle methods by creating a dummy
project in Eclipse and overriding all the lifecycle methods with log “debug” state‐
ments.
@Override
public void onPause() {
Log.d(TAG, "In method onPause()");
}

1.3 Learning About Android Releases


Ian Darwin

Problem
You keep hearing about Ice Cream Sandwiches, Jelly Beans, Lollipops and Marshmal‐
lows, and need to know what it all means.

Discussion
Android has gone through many versions in its lifetime. Each version has a version
number, a code name, and an API level. The Version Number is a conventional ver‐
sioning system like 2.1, 3.0, 4.0, 4.1, 5.0, 6.0, and so on. When the first digit of the
version changes, it’s a big deal with lots of new API; when the second digit changes,
it’s more evolution than revolution (and occasionally a new codename), and if only
the third digit changes, it’s a minor change. The API levels are numbered monotoni‐
cally. The code names are alphabetical and always refer to sweet foods. API levels 1
and 2 did not officially have code names.
Note that the Android system is backward-compatible in the usual sense: an app built
for an older release will run on a newer version of Android, but not vice versa. An

1.3 Learning About Android Releases | 21


app built for 1.5 should run without recompilation on Android 7, for example. But an
app written for and compiled on Android 7 will probably use API calls that don’t exist
on the 1.5 phone, so the phone will, in fact, refuse to install the newer app, unless you
use some versioning and compatibility stuff, which we’ll touch on later (Recipe 1.20).

Table 1-1. Android Versions


Version API Level Name Datea Major Change / Notes CM Version
Number
1.0 1 (none) 2008-09-23
1.1 2 (none) 2009-02-09
1.5 3 Cupcake 2009-04-30 3
1.6 4 Donut 2009-09-15 4
2.0 5 Eclair 2009-10-26 5
2.1 7 Eclair 2010-01-12
2.2 8 Froyo 2010-05-20 6
2.3 9 Gingerbread 2010-12-06 Long the most widely-used version 7
2.3 10 Gingerbread
3.0 11 Honeycomb 2011-02-22 Tablets only; source code release delayed
3.1 12 Honeycomb 2011-05-10
3.2 13 Honeycomb 2011-07-15
4.0 14 Ice Cream Sandwich 2011-10-19 Merge tablet and phone support 9
4.0.3 15 Ice Cream Sandwich 2011-12-16
4.1.2 16 Jelly Bean 2012-07-09 10
4.2.2 17 Jelly Bean 2012-11-13 10.1
4.3 18 Jelly Bean 2013-07-24 10.2
4.4 19 KitKat 2013-10-31 Co-marketing deal with Nestlé (makers of 11
KitKat chocolate bar)
5.0 21 Lollipop 2014-11-10 12
6.0 23 Marshmallow 2015-10-05 13
7.0 24 Nougat 2016-08-22
a Date information sourced from Wikipedia

The final column, “CM Version”, shows the main version numbers of CyanogenMod,
the leading “alternate distribution” of Android. Based on the Android Open Source
Project, “CM” is much beloved by many open-source fans because it is independent
of Google, allows easier “root” access, and so on. For more detail on CyanogenMod’s
history, see https://en.wikipedia.org/wiki/CyanogenMod#Version_history.
Of course this table will continue to grow as new versions are released, as Android
continues to grow!

22 | Chapter 1: Getting Started


1.4 Learning the Java Language
Ian Darwin

Problem
Android apps are written in the Java programming language before they are con‐
verted into Android’s own class file format, DEX. If you don’t know how to program
in Java you will find it hard to write Android apps.

Solution
Lots of resources are available for learning Java. Most of them will teach you what you
need, but will also mention some API classes that are not available for Android devel‐
opment. Avoid any sections in any resource that talk about topics listed in the left‐
hand column of Table 1-2.

Table 1-2. Parts of the Java API to ignore


Java API Android equivalent
Swing, applets Android’s GUI; see Chapter 6.
Application entry point main() See Recipe 1.2.
J2ME/Java ME Most of android.* replaces Java ME API.
Servlets/JSP/JSF, Java EE Designed for server-side use.

Discussion
Here are some books and resources on Java programming:

• Java in a Nutshell by David Flanagan (O’Reilly) is a good introduction for pro‐


grammers, particularly those who are coming from C/C++. This book has grown
from an acorn to a coconut in size, to keep up with the growth of Java SE over its
lifetime.
• Head First Java by Kathy Sierra and Bert Bates (O’Reilly). This provides a great
visual-learner-oriented introduction to the language.
• Thinking in Java by Bruce Eckel (Prentice-Hall).
• Learning Java by Patrick Niemeyer and Jonathan Knudsen (O’Reilly).
• “Great Java: Level 1”, a video by Brett McLaughlin (O’Reilly). This provides a vis‐
ual introduction to the language.
• Java: The Good Parts by Jim Waldo (O’Reilly).
• Java Cookbook, which I wrote and O’Reilly published. This is regarded as a good
second book for Java developers. It has entire chapters on strings, regular expres‐

1.4 Learning the Java Language | 23


Random documents with unrelated
content Scribd suggests to you:
bought she has also worked to mr alford blax and his
brother the old batchlor his mother was old and generly
done the niting she nit seventeen pare of socks and layed
them up for her boys when she got old and coldent nit no
more and they was all taken away by her to pare
afterwords was found at the store and she sed that she
had took them they owed her five dolars yet and they
wont pay her till she delivers the socks and she dare not
make no fuss for fear they will bring her out she worked
to mr cringlands and she hooked a pare of white kid
gloves and a hym book and a pocket handkerchief and the
gloves she traded away to the store for a dress by giveing
a pare of socks to boot and she worked to truman buts
this sumer she had taken a pare of stockin which they
found in her sunday bonet and they lost to shiling in
money and then they discharged her bengman grene
bought a set of dishes and they lost to platters out of the
set they lost sope and buter out of their sular she
borrowed of mister spicer a silver pen which coast a dolar
and after he was dead she denied haveing it and she told
it herself that she sold it for half a dolar and a pennife and
the pennife was fifty cents they borrowed a pale of wheat
flour and when they carid it home and put to thirds rie
The pepole most look out for them in the trincket line mr
sir post master plese answer this as soon as you can and
oblidge your friend much yours with respect
Direct your leter silas stickney North S——, N. Y.
The zeal of Silas, if he was actuated by no sinister motives—no spite
toward "the wider stacy and her to girls," especially "clarinda,"
whose exploits form the burden of his complaints—this zeal is highly
commendable, and united with it there is a fulness of specification in
the catalogue of "clarinda's" misdemeanors which equals in richness
and effect anything that even the fertile brain of Dickens could
conceive.
The ingenious device of sending ladies to the suspected domicil
under color of a friendly visit, but provided with a touchstone in the
shape of "a peic of cheese," wherewith to detect the other piece
supposed to have been purloined by some one of the thievish family,
was worthy of a Vidocq; and the triumphant issue of the case, when
their worthy Committee of Investigation "sliped a peic of cheese in
their laps" and settled its identity with the "inglich cheese" which the
victimized "shirtleff" had purchased, showed the power of genius,
attaining great ends by the use of simple means.
This epistle developes a new ramification of the postal system. A
post master entreated to act as a conservator of public morals; to
exert all his powerful influence against "clarinda," who proved
treacherous to "mr sam shirtleff" in the matter of pork and cheese;
and abstracted from "mr alford blax and his brother the old batchlor,
the seventeen pare of socks" that their mother had "nit" to comfort
their nether extremities when she, by reason of the infirmities of
age, "coldent nit;" and filched "sope and buter" out of "bengman
grenes sular;" to say nothing of the "pare of stockin" which were
secreted in her "sunday bonet," and "to shilling," the loss of which
occasioned her discharge from the service of "truman buts."
Upon this unfortunate post master was thrown the charge of seeing
that the city received no detriment from the demoralizing influence
of Clarinda!
This gentleman, not willing to be outdone by his correspondent in
his devotion to the public good, indited the following reply:—
B—— Post-Office, Dec. 13, 1854.
Mr. Silas Stickney.
Dear Sir:
I am in receipt of yours of the 19th ult., and in reply
would say that I cannot too highly commend your
solicitude in behalf of good morals, and your discretion in
selecting the post master of this place to carry out your
benevolent designs toward its inhabitants. The corrupting
influence of small villages upon large towns is a thing
much to be lamented, and it grieves me to think that the
unsophisticated inhabitants of this place are to be exposed
to the machinations of the "widow stacy and her to girls."
It will be, sir, like the Evil One entering the garden of
Eden, where all was innocence and purity!
If in the course of my official duties, I find it feasible to
ward off impending danger from this immaculate town, be
assured that I shall not fail to do so.
Yours, &c.
W. D
——, P. M.

But post masters are made confidants in graver matters than these.
They are not unfrequently called upon by deserted wives to look up
their truant husbands, and by desolate husbands to aid them in
recovering frail partners, who have been unfaithful to their marriage
vows, and have forsaken the "guides of their youth."
Letters of this description are principally from the more illiterate
class of community; yet amid the crooked chirography and bad
spelling, there sparkles so much tender affection, sometimes for the
guilty one, sometimes for the innocent children, who are suffering
from the unprincipled conduct of a parent, that these cases
command the warmest sympathy of those whose aid is invoked,
although the requests thus made relate to matters entirely out of
their sphere, and consequently they are seldom able to afford much
assistance to the parties in trouble.
I will here give an extract from this class of letters, as illustrating the
above remarks. The following is from a letter received by the post
master of a city in Ohio, from a woman who had been deserted by
her husband five years previous. She requested the post master to
read it to her husband, in case he should find him, so it is written at
the latter person. In the postscript, (which is generally supposed to
contain the pith of female correspondence,) she says,—
"You would shed tears If you onley could see wat a smart
peart little boy you have hear what a sham It Is to think
that A sensable man should leave a wife and a child that
Is got as much sense as he has—and people say he is as
much like you as he can be he has got the pretys black
eyes I have ever seen In any ones head he has an eye like
a hawk."
Thus is the argumentum ad hominem supplied by woman's instinct.
Fatherly pride was called upon to effect that to which conjugal
affection was inadequate.
CHAPTER XXVII.
A Windfall for Gossipers—Suit for Slander—Profit and Loss—The
Resuscitated Letter—Condemned Mail Bag—An Epistolary Rip Van
Winkle.
In country villages, where few events happen to interrupt the
monotony of every day life, the occurrence of an out-of-the-way
incident is like seed sown in a fertile soil, producing a fruitful crop of
speculations and surmises, and affording food for conversation for
many a day to the eager gossip-hunters who abound in such small
places.
About thirty years ago, the quiet town of Lebanon, in the State of
Connecticut, was enlivened by one of these occurrences, which
brought a new influx of curiosity-mongers to the blacksmith's shop;
covered all the barrels, boxes, and counters in the store with eager
disputants, and gave new life to the Sewing Society, and its auxiliary
"tea-fights." The cause of this unwonted moving of the waters, was
on this wise:
Mr. Jonathan Little, a well known New York merchant, while on a
summer visit to Lebanon, his native place, mailed at that office a
letter directed to the firm of which he was a member, and containing
bank-notes to the amount of one thousand dollars. The letter failing
to arrive at its destination, and Special Agents being as yet
unknown, Mr. Little advertised in several papers, describing the
money lost, and offering a reward for its recovery. This, however,
produced no results, and the tide of speculation and discussion rose
to its highest pitch.
The loss of the bewildering sum of one thousand dollars naturally
stimulated the imaginative powers of the Lebanonians, and, hurried
away by his zeal, or perhaps by a wish to appear sagacious, Mr.
Roger Bailey, the brother of the Lebanon post master, while in
conversation with several persons, incautiously asserted that Amasa
Hyde, the post master at Franklin, (the next town to Lebanon on the
route to New York,) had taken the letter, adding, "He's just such a
fellow."
The by-standers were rather astonished at this bold charge,
impeaching as it did the integrity of a man whose character had
always been above suspicion. That "bird of the air" which is always
ready to "carry the matter," soon diffused the information that
Amasa Hyde was supposed to be the delinquent. This gentleman
being indisposed to leave his reputation at the mercy of "thousand-
tongued Rumor," which personage could not easily be brought
before a jury, instituted inquiries for the purpose of discovering the
originator of these injurious reports. He succeeded in tracing them to
their source, and sued the unwary Bailey for slander. Mr. B., by the
verdict of the jury, was compelled to pay some seven hundred
dollars and costs, for the pleasure of expressing his opinion.
This, however, is but an episode in the history of the lost letter. After
a while the excitement died away, and Mr. Little found it necessary to
place the thousand dollars to the account of "Profit and Loss,"
especially the latter.
The theory was once advanced by an acute genius, and applied to
the case of a tea-kettle inadvertently dropped into the ocean, that "a
thing isn't lost when you know where it is." But the subject in hand
seems to show that a thing isn't always lost, if you don't know where
it is. For, about two years after the occurrences above mentioned,
the missing letter came to light with all its valuable contents. And
this resuscitation took place, not in Lebanon, nor in Franklin, but in
the New London post-office!
It appears that the mail bag which contained the letter, was found,
on its arrival at New London, so much worn as to be unsafe, and
was accordingly condemned by the post master and thrown aside as
useless, having first, of course, been emptied of its contents, as was
supposed. Two years subsequently, a quantity of old mail bags and
other rubbish was removed from the office, and the letter in
question took the opportunity to drop out, and return, an epistolary
Rip Van Winkle, to the world whence it had retired for so long a
time.
CHAPTER XXVIII.
VALENTINES.

Their Origin—Degeneration—Immoral Influence—Incitement to


Dishonesty.
Who Saint Valentine was, is not much to the purpose in this place.
We will give him credit for having been, however, a very excellent
and highly respectable individual. We must therefore utterly protest
against the custom which has obtained of late years, making him the
tutelary Saint of innumerable silly lovers, mean mischief-makers, and
vulgar letter-writers generally.
Unfortunately for the reputation of this inoffensive Bishop, the day
noted in the calendar as sacred to his blessed memory, happens to
be that on which, according to the auld-wives' legends of Merrie
England, there is a universal marrying and giving in marriage among
the feathered tribes. The Fourteenth of February seems rather bleak
for a grand wedding festival at which any birds but snow birds are
expected to attend; but we suppose we must respect the tradition. It
seems early too for imitative lads and lasses, who should wait until
the warm spring approaches;

"When the South-wind in May days.


With a net of shining haze.
Silvers the horizon wall.
And with softness touches all—
Tints the human countenance
With a color of romance;"

and when all nature is bathed afresh in light and love, and inspired
with new life.
But, says a French writer, the divine faculty which distinguishes man
from the brutes, is the capacity to drink when he is not thirsty, and
to make love at all seasons of the year. Whether this "divine faculty"
is a God-gift, or a perversion and abuse, the legitimate fruit of the
sad tree of knowledge of good and evil, we will not stop to discuss.
Man has it in full exercise; and however the birds may grumble at
being obliged to hurry up their matrimonial cakes under the very
beard and brow of winter, Cupid will be found—like the classical
clothes-brusher and job-waiter—"nunquam non paratus"—always
ready at your service.
The probability is that the human custom of choosing mates about
this time, is more ancient than the notion touching the pairing of
birds, and that the latter is a mere fable, suggested by the former.
Some commentator on Shakspeare has traced it back "to a pagan
custom of the same kind during the Lupercalia feasts of Pan and
Juno, celebrated in the month of February by the Romans. We are
further told that, the anniversary of St. Valentine happening in this
month, the pious promoters of Christianity placed this custom under
his patronage in order to indicate the notion of its pagan origin."
Unhappy St. Valentine! But we must remember that formerly there
was something sweet and poetical in the choosing of mates. Now we
are thrilled with tender emotions when poor Ophelia sings her
"Good morrow to St. Valentine's-day."
But somehow, romance dies out in our material age; and beautiful
superstitions give place either to cold practical knowledge, or
degenerate into farcical caricatures. What a difference between the
rapturous and bashful exchange of vows pledged by the youth and
maidens in good old times, before reading and writing came in
fashion, and the celebrated Valentine composed by the younger Mr.
Weller! The vulgarization of the custom has been gradual. Instead of
the song-singing invitations to love, under cold windows,
"All in the morning betime,"
lovers began, in the course of human progress, to indite gentle
missives to their sweethearts, and to receive autograph replies. This
improved method was eagerly adopted by all such as dared not give
verbal utterance to their sweet passion, as well as by those who had
private malice to vent, and sneaking insults to offer. Then arose the
manufacture and merchandise of Valentines, which has of late
become so important a branch of industry.
From early in February until late in March, our toy shops and
periodical and fancy "depots" appear to traffic mainly in these
exceptionable articles. Their windows flame with the vulgar trash.
On every corner "Valentines!" "Valentines!" stare us in the face.
Some are very choice and costly; we see now and then one inlaid in
a rich casket, and prized at twenty-five or even fifty dollars. Others
are made of fine fancy paper, adorned with flowers in water colors,
or prettily filigreed; with a scroll in the center for the verses
expressive of the sender's sentiments.
But the softer heads that indulge in these expensive trifles, are
comparatively few. A cheaper luxury satisfies our economical
sentimentalists. All kinds of coarsely ornamented note-paper, and
large square awkward envelopes, find their ready patrons. Every
taste is suited, from the sickliest fastidiousness, to the most clownish
ambition for flashy colors and tawdry designs.
In opposition to the sentimental Valentines, we have the gross
caricatures which have done more than anything else of this kind to
disgust the common sense and good taste of community. It would
seem that only the most vulgar minds could be attracted by these;
yet the large traffic in them shows that vulgarity is an extensive
element in the popular character. No matter how indelicate and
disgusting one of these specimens of low invention may be, some
fool will be found to purchase it, and send it to another individual
whom he either wishes to insult or expects to amuse.
In this way all sorts of printed immoralities obtain circulation. In this
way cowards take revenge for imaginary slights or dignified
rejections. In this way, for about two or three weeks in each year,
some altogether harmless and well-meaning people have been
subjected to gross annoyances and serious taxes for postage.
Thanks to the law-makers, the advance pay requisition will hereafter
put a stop to that species of petty swindling.
Year after year the same foolish figures and senseless mottos are
forwarded from the same simpletons to the same victims. We know
a musician who for three successive seasons has received that
witched caricature, representing a shape—
"If shape it could be called that shape had none,—"
all nose and moustache, blowing a trombone considerably larger
than himself.
Our dentist usually enjoys a visit from a caricature suited to his
profession—a tooth-drawer with his little head in a vast chasm
representing a young lady's mouth. He has learned to expect it; he
good-naturedly looks for it, about Valentine's day; and merely
opening it when it comes, to see that it is the right one, he quietly
tosses it into the fire.
This Valentine sending is a custom like that of a certain drunken
revel once popular in Denmark,—"More honored in the breach than
in the observance." It is ignored by good society. And as for the
victimized, it is a mark of common sense to bestow every Valentine
into the grate, unopened, as soon as received.
It is estimated that not less than half a million of these worse than
worthless missives pass through the post-offices annually. The cost
to the parties purchasing them, forms an aggregate of about
$200,000. Over and above this expense is the postage, which is
sometimes double, triple, or even four or five times the ordinary
rates of single letter postage. Formerly many were unpaid, and often
persons to whom they were addressed, indignantly refused to take
them from the office. Thus were the mails not only uselessly
encumbered with the vile trash, but quantities of the "rejected
addresses" were subjected to the formality of visiting the Dead
Letter Office, where they finally met with that destruction they so
clearly merited. This abuse of the post-office privileges is unworthy
of any nation above the capacity of monkeys.
The immoralities circulated and encouraged by Valentines cannot be
estimated. Statistics would fail to arrive at the amount of vice
engendered by this pernicious breed. One of the worst evils that
owe their origin to this cause, is the temptation laid in the way of
post-office clerks. A Valentine is often the first provocation to crime.
Numerous instances have come under the observation of the writer,
in which persons convicted of robbing the mails, trace back their
transgressions to no more serious a fault than that of peeping into
one of these silly missives. They are often carelessly sealed, and
easily opened by third parties without discovery.
Imagine a young man intrusted with the care of a village post-office.
He is interested in Miss A. He believes she encourages his
sentiments. He hopes her proud father will some day encourage him
as an eligible suitor for his daughter's hand. Still he is subject to
desponding and jealous doubts. And when, one evening in the
middle of February, a Valentine addressed to his paragon strikes his
eye as he is assorting the mails, an indescribable pang shoots
through his heart. He wonders who sent it. Tom Bellows is at first
suspected, but the hand-writing differs from Tom's. "Can it be Robert
Cartwright?" says the distressed clerk. "He is partial to Miss A., and
she seems pleased with him. What can he be writing to her?"
Such thoughts perplex the young man's brain. The Valentine is not
taken from the office that evening; and when all is quiet, he draws it
once more out of the box, and again examines the superscription. It
is certainly Cartwright's writing. "O dear!" sighs the clerk, "how easy
I could open it, and nobody know it!" Aching with curiosity, but
calling moral principle and self-denial to his aid, he returns the
missive to the box, and goes to bed. But sleep is out of the question.
He is awake, thinking about the Valentine, and those supposed to be
immediately interested therein. "I wonder if I could open it!" he says
to himself. "I've half a mind to try."
He gets up, strikes a light, and a moment later the Valentine is in his
hand. "If it comes open," says he, "I'll seal it again without reading
it. I only want to see if it can be done without having it show
afterwards." Instantly he starts back. The Valentine is open! Really,
he did not mean to do it; it came open so much easier than he
expected! Although it is night, and he is alone, he cannot help
looking over his shoulder to assure himself that the grim individual
watching him, exists only in his imagination. "Well," thinks he, "it's
done, and who knows it? What's the harm, as long as I'm going to
seal it up again?—and after all, I don't see that it will be much worse
just to see if there is any name to it, provided I don't read the rest."
Thus excusing himself, he profanes the sacred interior of the
missive, and finds the suspicious signature—"Robert." Trembling at
the temptation to read more, he hastily folds the sheet, and returns
it to the envelope. But the next moment it is out again, and he is
reading with flushed cheek and burning eye, the tender words that
Robert C. has written to Miss A.
"All this hath a little dashed his spirits;" and he returns to bed
feverish and restless. In spite of his reason, which keeps saying
stoutly, "what's the harm? nobody will know it," he suffers greatly in
conscience. But the Valentine is taken from the office, and the
profanation of its mystery remains unsuspected. And in a few days
another Valentine appears, addressed to Robert Cartwright. The
hand-writing, although disguised, is alarmingly like Miss A.'s. By this
time the clerk's jealousy has eaten up his conscience.
"There's no more harm in opening two than in opening one,"
whispers the devil in his ear.
"I believe you," says the clerk; "but I may yet be found out."
"No danger," says the devil; "only be careful."
He is too ready to adopt the suggestion. He is excusable, he thinks,
under the circumstances. The Valentine is accordingly opened and
read. Deliberation and forethought add gravity to the offence. The
clerk has unconsciously blunted his moral perceptions, and
weakened his moral strength; and he is now prepared to open
regular letters passing through his hands. At first it is jealousy and
rivalry that tempt his curiosity. Then other matters of interest entice
him, until one day he discovers, in no little consternation, that he
has thrust his fingers into a nest of bank-notes!
"Well, after all," says he, "Mr. B. is rich; he won't mind the loss; it's
only a trifle with him. While to me, the sum is considerable. If I don't
keep up appearances with Bob Cartwright, I might as well be out of
the world. I've a right to live; and destroying this letter and
appropriating its contents, is just nothing at all, if I don't get found
out. But I'm safe enough—I'm the very last person to be suspected."
The career of this young man need not be traced further.
Nor need the subject of Valentines be pursued. We have written
enough to show that they are the offspring of weak sentimentalism
or foolish buffoonery; an encumbrance to the mails, an annoyance
to those who receive them, a tax to all parties, and a temptation to
post-office clerks; and withal, imbecilities and immoralities which all
worthy citizens should take every occasion to discountenance, and
banish from civilized society.
CHAPTER XXIX.
THE CLAIRVOYANT DISCOVERY.
A short time after the detection of the New Haven mail robber, a
gentleman from the town of W. called upon the post master at
Hartford, to say that he had some weeks since mailed a letter at the
post-office in the town where he resided, addressed to a firm in
Hartford; and containing a sum of money, and that the letter had
never been received.
On examining his records, the post master ascertained that no bill
had been received from the office where the letter was mailed
corresponding with the date of the mailing, and that consequently
the letter, so far as his records could show, had never reached his
office.
As the time of this loss happened at the period when the mail robber
was committing depredations from day to day, and as the post-bill
was missing, the Hartford post master expressed the opinion that
the letter had very probably fallen into the hands of the mail robber,
although New Haven was off the route on which the letter should
go, and the package of letters could not have got there without
having been mis-sent.
This theory was entirely unsatisfactory to the gentleman who mailed
the letter, and he left Hartford with the conviction that he would be
compelled to endure the loss of his money with such philosophy as
he could summon to his aid.
But hope soon succeeds fear, as daylight follows darkness, and
before many days the gentleman in search of his money again called
at the post-office in Hartford, that being the important port in his
voyage of discovery.
It was very evident that his mind was somewhat "exercised," and
the ominous tone in which he requested the post master to meet
him immediately, at room No. —— at the hotel where his name was
entered, made it clear that a revelation of no slight importance was
about to be made.
The post master told him he would accompany him immediately, and
started with his eager friend for the appointed place. During their
walk nothing was said on the great subject-matter, probably because
it was deemed too solemn in its nature to be broached amid the
bustle and jar of a crowded street.
The hotel was soon reached, and the communicator of the "latest
intelligence" ascended the stairs to the room where the gentleman
accompanying him would be called on to listen to the disclosures
about to be made, and take such action thereon as circumstances
might seem to require.
After pointing solemnly to a chair, declaring by such dumb show that
he desired the post master to be seated, and then taking a chair
himself and sitting thereon so as to face the person with whom he
was conversing, he deliberately asked—
"Do you believe in clairvoyance?"
What an unexpected question! And how should such a question be
noticed? Certain it was that among all the laws in relation to the
Post-Office Department, and the rules and regulations for its
government, minute and circumstantial as they were, not one word
could be found instructing the officers of this branch of Government
what they should do in the matter of clairvoyance. Even Ben Franklin
himself, who was "par excellence" the electrical Post Master General,
had never issued an order bearing on this subtle subject. And here,
in this hotel room, where, at a great many different times, a great
many different kinds of spirits had entered a great many different
kinds of persons, this official in a great business Department, dealing
constantly with the practicalities of life, and without law, rules, or
regulations to tell him what he should do in the emergency, was met
with the question proposed, in a sepulchral voice,—"Do you believe
in clairvoyance?"
Was it his duty to discuss with the questioner the "Odic force," and
"Biology" and "Psychology," and all the other theories connected
with the doctrines of spiritualism? Must post masters be also masters
of mental science, and of things in heaven and earth never dreamed
of in the philosophy of the great mass of mankind? Because they
have to deal with the transmission of intelligence to different parts of
the earth, must they also take charge of intelligence coming from
unknown regions, "out of space, out of time?"
The question, however, was before him, and the post master replied
that he had heard of some strange things connected with
clairvoyance.
Seemingly satisfied with this reply, the gentleman went on to say
that he had been very anxious to know what had become of his
letter, and had therefore consulted a clairvoyant.
Some locations are blessed with a gifted seer, or more generally
seeress, whose mind at inspired intervals is a complete "curiosity
shop" of the universe—who can tell the whereabouts of a lost
thimble or teaspoon, who can inform the anxious inquirer who
committed the last murder, and who can describe to eager listeners
the manner in which people conduct voiceless conversation in
Saturn, and how they fight in Mars, and how they make love in
Venus. Or the gifted one, descending rapidly to earth, can prescribe
a remedy for any ill that flesh is heir to,—and all these wonders are
performed for a moderate pecuniary compensation, and with the
praiseworthy object of aiding and enlightening "suffering humanity."
Our inquiring friend was so fortunate as to reside in one of these
localities, and his mission to the post master was that of rehearsing
the discoveries of the Priestess.
He stated that the information given by the clairvoyant lady was so
minute and distinct as to leave a strong impression of its truthfulness
on his mind. That she traced the letter from the time it was put in
the office—saw it placed in the mail bag, saw the bag taken from the
office, saw every station where it stopped—saw it taken into the
Hartford office—saw it opened there, saw a clerk take the letter,
open it, and on finding that it contained a number of bank-bills, put
said letter in a drawer of his, and then lock the drawer.
Farther than this, the Seeress declared that said clerk wore large
whiskers, and a large gold ring, and that he resided in Front Street.
In addition to these facts the lady declared that the letter thus
opened, with the bills still in it, was yet remaining in the locked
drawer of the delinquent clerk.
Having carefully repeated this train of circumstantial evidence,
pointing so distinctly to a certain culprit, the gentleman then
commenced interrogating the head of the Hartford post-office:—
"Have you, sir," said he, "a clerk in your employment who wears
whiskers?"
The witness was compelled, on the part of some of his clerks at
least, to plead guilty to this first count in the indictment from an
invisible Grand Jury. As whiskers are not an expensive article of
luxury, even post-office clerks can afford to wear them.
"Have you," continued the counsel for the unknown prosecutor, "a
clerk who wears large whiskers and a large gold ring?"
The reply to this query was not equally satisfactory, for the witness
averred that his clerks were decidedly not given to jewelry; and as to
gold, they felt that they could invest it more usefully than in the
purchase of mammoth finger-rings.
"Have you," continued the pertinacious querist, "a clerk who lives in
Front Street?"
Here again the answer was not gratifying, for the witness declared
that to the best of his knowledge, no clerk of his had, whether with
or without whiskers, or whether with or without a stupendous finger-
ring, made Front Street illustrious by residing therein.
Notwithstanding the discrepancy, the gentleman went on with his
inquiries:—
"Have you a clerk in your employment who has a drawer of which he
keeps the key?"
The reply to this question was such as to meet the wishes of the
querist, and he was told that there was more than one such clerk in
his office.
"Then," said the gentleman, "I demand that you have those drawers
opened, and their contents examined!"
Notwithstanding the urgent desire of the person who had reposed
such confidence in the revelations of the female informer, the post
master peremptorily declined to take a single step implying a doubt
as to the integrity of his clerks, on the mere strength of clairvoyant
testimony.
Argument was in vain, and the disappointed letter seeker left
Hartford, thinking in all probability that General Pierce would have
done better to have given the charge of the office there to some
person more willing to accommodate the public!
Some time after this, the Special Agent met the post masters of New
Haven and Hartford, in pursuance of instructions from the
Department, for the purpose of distributing the funds taken from the
depredator, among those who had lost by the robberies.
On examining the money found on the person of the robber, there
were discovered the seven bank-bills, all of one denomination, lost
by our clairvoyant-seeking friend! The bills not only agreed with his
description, but, what made the case still stronger, was the fact that
no other bills of the same denomination and bank were claimed by
any other party.
How it was that "the Spirits" gave the distinguished seeress such a
complete tissue of falsehoods, will probably remain unknown until
the "new philosophy" becomes better understood, or until the Spirit
of Franklin, who it is said presides over communications from the
upper spheres, appoints some Special Agent to investigate the
causes of failure.
The gentleman who unexpectedly regained his money, may still
entertain his old affection for clairvoyance, but he cannot deny that
the poet was right when he exclaimed,

"Optics sharp it needs, I ween.


To see what is not to be seen."
CHAPTER XXX.
POETICAL AND HUMOROUS ADDRESSES UPON LETTERS.
The exterior, as well as the interior of a letter is sometimes made the
vehicle of sentiment, affection, wit, fun, and the like, which, thus
riding as outside passengers, display their beauties to the gaze of
those connected with post-offices. In such instances, it may be that
the writer's ideas, gushing from his pen, have overflowed their
bounds, and spread themselves upon the usually dry surface of the
epistle. It must be a pleasing relief to post-office clerks, wearied with
the monotonous task of turning up innumerable names, to find the
flowers of fancy and imagination supplanting the endless catalogue
of Smiths and Browns which ordinarily meet their eyes. Below are a
few specimens of these embellished addresses.
The first is probably from some home-sick miner. It was mailed at
San Francisco, California. His wife and children have no doubt
derived, long ere this, the pleasure which he anticipated for them, in
the perusal of the letter:—

Go, sheet, and carry all my heart;


(I would that thou couldst carry me,)
Freighted with love thou wilt depart
Across the land, across the sea.

O'er thee will bend a loving face.


To thee will listen little ears;
Thou wilt be welcomed in my place.
And thou wilt bring both smiles and tears.

Across the land, across the sea.


Thy homeward course thou wilt pursue.
I may not see them welcome thee.
Yet know I well their hearts are true.

Then swiftly go, thou ocean steed;


Roll on, ye rapid iron wheels.
Bearing away, with careless speed.
The message that my soul reveals.

The address followed, in plain prose.

Rail road, steamboats, horses, stages.


All of you are paid your wages.
All of you, for nothing better
Than to take this little letter.
Should the document miscarry.
Uncle Sam will see "old Harry!"
To prevent this dread collision.
I present unto your vision
State, county, and between, the town.
Indiana, Nashville, Brown.
For Mrs. Jane Eliza Brent.
This is enough,—now "let her went."

Here is a specimen in a less elevated strain:—

Robber, shouldst thou seize this letter.


Break it not; there's nothing in't.
Nought for which thou wouldst be better:
Note of bank, or coin from mint.

There is nothing but affection.


And perhaps a little news;
When you've read this, on reflection.
Take or leave it as you choose.

If you should conclude to leave it.


I would like to have it go
To Seth Jones, who will receive it
In the town we call Glasgow.
And the state of old Kentucky,
(There's no rhyme for that but "lucky.")

The following seems to have been the superscription to a dun,


written "more in sorrow than in anger."

A hard old hoss is Charley Cross.


And I don't care who knows it;
He's borrowed an X, and never expects
I'll dun him, so he goes it.

He'll find he's mistaken, and won't save his bacon.


Unless he sends me the tin:
In the city of Penn, somewhere is his den;
I can't tell what state he is in.

Perhaps he's "slewed," or may be, pursued


By some other man he owes.
Whichever it is, when this meets his phiz.
My account he had better close.

The street and number were subjoined; but it is to be feared that


the "old hoss" proved hard-bitted, and would have nothing to do
with "checks," except those in his favor.
Post master dear.
I greatly fear
That this letter never will go
To him I write.
Unless to your sight
The name I plainly show.

'Tis Thomas Brown.


The name of his town
Is Hartford; the county the same.
Land of steady habits.
Famed for onions and rabbits.
The place whence once I came.

This is apparently an outpouring of the sorrows of a victim to the


Maine law, and was mailed in that state:—

Oh John O'Brien, half of you is better than the whole.


For that would be a Demi-John, my sorrow to console.
Oh dear O'Brien, briny tears into my whiskers roll.
To think that you live in New York, while here is not a soul
To stand treat; or in other words, to "pass the flowing bowl."

All flesh is grass: all paper's rags,


(So it is said by wicked wags.)
But I would like to pass along
Among th' epistolary throng.
Till I reach the town of Kent
Nor to a paper mill be sent.
And come to an untimely end.
Before I find my writer's friend;
Whose name is Putnam, or Sam Put.
In the old State Connecticut.

This is going to my tailor.


A trust-worthy man is he;
Like a clock, for ever ticking.
He keeps his account with me.

To send my bill I here request him


For the br—ches he has made:
Thanks to good old uncle Samuel.
He must send it on pre-paid.

(The address was in prose.)

When you C this letter.


You'd better letter B.
For it is going over
Unto Tom McG.
In the town of Dover.
State of Tennessee.

Address on a Valentine:
Mr. Post Master, keep this well,
for every line is going to tell
how much I love my Bill Martell.
Syracuse, N. Y.

I want this letter to go right straight


To Wilmington city in Delaware State.
To Daniel B. Woodard, a cooper by trade;
He can make as good barrels as ever were made.

Swiftly hasten, Postman's organ.


Bear this onward to its fate.
In New York to George C. Morgan;
John Street, No. 78.

East 10th Street, City of New York.


Two hundred fifty-three—
Is where of all this little work.
This moment ought to be.

And could I to the lightning's wing


Or telegraphic wire.
Attach it by a silken string,
'Twould be my fond desire.
But since to do the swift exploit
Each other power must fail.
I send to Emily Bailey Hoyt.
With pleasure—in the mail.

I know a man, his name is Dunn!


He lives in splendid style:
But if he'd pay—say half his debts.
He'd lose 'bout all his "pile."

He stops in Charlestown, old Bay State.


Quite near to Bunker Hill.
Where many a brave man met his fate.
Dispensing Putnam Pill.

A VALENTINE ADDRESS.

Lizzie, they say the little birds


Are making matches now;
(Warranted to keep in any climate.)
A good example they have set
Which I would like to follow;
So if you have a heart to let.
I hope to know to-morrow.
On the river Hudson.
In the town of Troy.
Lives Miss Sarah Judson
Full of life and joy.

'Tis for that sweet creature


This epistle's meant;
If it does but reach her.
I shall be content.

The following address was found on a missive which passed through


the New York office on or about the 14th of February, and was
secured with a seal representing Cupid taking aim at one of his
victims with a revolver:

Cupid's mother has supplied him


With "six shooters" for his bow;
When he'd arrows I defied him;
Now, alas! he's laid me low.

Here I send, done up in paper.


Fanny May, my heart to you.
I think you will keep it safer
Than I've done,—so now adieu.

The town and state were in prose.


Send this, Post Master, if you are willing.
To John M. P——, a darned old villain.
Let it go without Postage Bounty.
To Union Valley, Cortland County.

Take me along in haste I pray.


To John O'Donnel without delay.
The postage is paid, there is no excuse
If I'm not delivered at Syracuse.

Let nought impede thy progress.


While on thy journey going.
And quickly may'st thou be received.
By John, or Pardon Bowen.
Albany, N. Y.

Miss Kate May,


Somewhere in New York City.
I hope to goodness she will receive
this missive.

John M. Simpson, Dedham.


Mill Village.
Mass.
in care of John Lee,
the man that speaks through
his nose or with the crucket foot.

For Nevel Kelly, Degrau St.,


next shanty to the river in the rear
of the grave-stone yard.
Brooklyn, N. Y.

New Haven, post-office


State of Connecticut
Brown Street
Number 58
For elen Rumford
under care of mister allen
And if the main law folks up there don't like the name of Rumford
i can't help it.

for
Brigded Livingston no 16 post
office city Hartford, State of
Cannada or three-ways to No 39
America.
To Thos. Walsh 362 3rd Avenue
or if not there (New York
To the care of America
Jerrimiah O Droyer—No—173
South street South Troy New York
To be forwarded
To Mary Dohorty (For Thos. Walsh
(in haste America

To Mr. Leedfara, who runs the ferry


over across to Long Island for Mary
Maguire New York.

Mistress Crovor Keeps


a stand in the
hutson dippo—New York
lives in reed street.

Direct this letter to


315 Second floor
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like