Android Cookbook 2nd [early release] Edition Ian F. Darwin download
Android Cookbook 2nd [early release] Edition Ian F. Darwin download
https://ebookname.com/product/android-cookbook-2nd-early-release-
edition-ian-f-darwin/
https://ebookname.com/product/java-cookbook-4th-edition-ian-f-
darwin/
https://ebookname.com/product/java-cookbook-1st-edition-ian-f-
darwin/
https://ebookname.com/product/android-application-development-
cookbook-second-edition-rick-boyer/
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/
https://ebookname.com/product/autism-your-questions-answered-1st-
edition-romeo-vitelli/
https://ebookname.com/product/developing-teaching-and-learning-
in-higher-education-1st-edition-gill-nicholls/
https://ebookname.com/product/crisis-cause-containment-and-cure-
second-edition-thomas-f-f-huertas/
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 .
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
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
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.
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.
xii | Preface
This icon signifies a tip, suggestion, or general note.
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.
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.
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:
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!
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.
Of these, the Activity is the most basic component, and the place you need to start
when learning to develop Android applications.
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.
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.
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
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!
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.
Discussion
Here are some books and resources on Java programming:
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.
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,
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.
A VALENTINE ADDRESS.
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
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.
ebookname.com