SlideShare a Scribd company logo
Android Cookbook 2nd [early release] Edition Ian
F. Darwin 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/
Android Cookbook 2nd [early release] Edition Ian F. Darwin
Android Cookbook 2nd [early release] Edition Ian F. Darwin
Ian Darwin
Android Cookbook
SECOND EDITION
978-1-449-37445-7
[FILL IN]
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
Production Editor: FILL IN PRODUCTION EDI‐
TOR
Copyeditor: FILL IN COPYEDITOR
Proofreader: FILL IN PROOFREADER
Indexer: FILL IN INDEXER
Interior Designer: David Futato
Cover Designer: Karen Montgomery
Illustrator: Rebecca Demarest
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.
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…
Android Cookbook 2nd [early release] Edition Ian F. Darwin
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
Number
API Level Name Datea Major Change / Notes CM Version
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
KitKat chocolate bar)
11
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
Another Random Document on
Scribd Without Any Related Topics
Android Cookbook 2nd [early release] Edition Ian F. Darwin
Android Cookbook 2nd [early release] Edition Ian F. Darwin
Android Cookbook 2nd [early release] Edition Ian F. Darwin
The Project Gutenberg eBook of Among the
Humorists and After Dinner Speakers, Vol. 1
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.
Title: Among the Humorists and After Dinner Speakers, Vol. 1
Editor: William Patten
Release date: October 31, 2012 [eBook #41249]
Most recently updated: October 23, 2024
Language: English
Credits: Produced by D Alexander, Matthew Wheaton and the Online
Distributed Proofreading Team at http://www.pgdp.net
*** START OF THE PROJECT GUTENBERG EBOOK AMONG THE
HUMORISTS AND AFTER DINNER SPEAKERS, VOL. 1 ***
AMONG the HUMORISTS
and
AFTER DINNER SPEAKERS
OLIVER HERFORD
AMONG THE HUMORISTS
AND AFTER-DINNER
SPEAKERS
A NEW COLLECTION
OF HUMOROUS STORIES
AND ANECDOTES
SELECTED AND ARRANGED BY
WILLIAM PATTEN
Editor of American Short Story Classics,
Foreign Short Story Classics, etc.
VOL. I
P. F. COLLIER & SON
NEW YORK
Copyright 1909
By P. F. Collier & Son
PARTIAL LIST OF THE NAMES OF
STORY-TELLERS IN THIS VOLUME
George Ade Sir Wilfrid Laurier
Bret Harte Oliver Herford
Mark Twain J. M. Barrie
Sec. of State P. C. Knox Richard Mansfield
W. M. Evarts John Sharp Williams
De Wolf Hopper J. G. Blaine
King Edward of England Phillips Brooks
Joseph Jefferson Daniel J. Sully
Lord Beaconsfield Bill Nye
Abraham Lincoln John C. Spooner
Alvey A. Adee Robert Edeson
Patrick A. Collins Andrew Lang
Horace T. Eastman Benjamin R. Tillman
D. G. Rossetti William E. Gladstone
J. M. Maclaren Charles Lamb
Dean Swift Edwin Booth
Clyde Fitch Weedon Grossmith
J. McNeill Whistler Senator W. A. Clark
Leigh Hunt Francis Wilson
Edward Everett Hale Chauncey M. Depew
Dean Hole Albert J. Beveridge
Irving Bacheller Beerbohm Tree
Thomas B. Reed Herbert S. Stone
J. C. S. Blackburn Frank R. Stockton
N. C. Goodwin Henry James
Brander Matthews William Allen White
Andrew Carnegie Bishop Brewster
Speaker Cannon Frederic Remington
Walter Damrosch Julian Ralph
Rev. Robert Collyer Senator John T. Morgan
Rev. Sam Jones J. J. Ingalls
Dean Kirchwey Archbishop Ryan
John Wanamaker J. A. Tawney
Henry Guy Carleton Thos. Bailey Aldrich
Charles Francis Adams Elihu Root
T
PREFACE
HE collection of these humorous paragraphs has extended over
a number of years. Even a small beginning became a source of
such entertainment that the collection grew and grew, always
without any thought of publication.
The man who can not laugh has yet to be found. Therein lies that
immediate appeal to a common ground which the sense of humor
gives, and it has been a conspicuous characteristic of those who look
to the public for appreciation and support. Lord Palmerston and
Abraham Lincoln were two notable examples of men for whom
sympathy quickened through their ready wit, and no political
speaker drives home his arguments half so well as he who can
introduce a witty illustration. The joke has ever been a potent factor
in combating oppression and corruption, in ridiculing shams. It has
embalmed some reputations, and has blasted others. It is the
champion of the weak against the strong, and has often illuminated
for us, as in a flash, a glimpse of character or custom that would
otherwise have been lost to the world.
There is only one similar collection of which I am aware, the “Jest
Book” by Mark Lemon, who was for twenty-nine years the editor of
“Punch.” Alas that there should be fashions in jokes as well as in
hats, for much of his book that we know must have been humorous
reading to his contemporaries, leaves us, of the present generation
in America, indifferent.
I shall be glad if some of my readers are minded to do a graceful act
and send me, in return, some paragraphs to add to my collection.
I wish to take this opportunity to thank the following publications for
the paragraphs borrowed from their columns:
Evening Sun, Lippincott’s, Pittsburg Dispatch, San Francisco News-
Letter, Ladies’ Home Journal, Washington Star, Mail and Express,
Youth’s Companion, Life, Good Housekeeping, Argonaut, Buffalo
Commercial, Tit-Bits, Punch, The Tattler, Harper’s Weekly, Harper’s
Monthly, Democratic Telegram, Cleveland Plaindealer, Harvard
Lampoon, Judge, Philadelphia Ledger, Saturday Evening Post,
Philadelphia Evening Bulletin, Boston Herald, Kansas City Star,
Washington Post, Success, Atchison Globe, New York Times,
Woman’s Home Companion, London Mail, Louisville Courier-Journal,
Rochester Post-Express, New York Tribune, New York Observer,
Chicago Daily News, Pittsburg Post, Pittsburg Observer, Philadelphia
Public Ledger, New York World, Pick-me-up, Harper’s Bazar, The
Green Bag, Tacoma Ledger, Pittsburg Dispatch, The Wasp, Cornell
Widow, Washington Post, Kansas City Independent, Short Stories.
W. P.
T
AMONG THE HUMORISTS AND
AFTER-DINNER SPEAKERS
HERE is a delicious flavor about this story of a Virginia lady,
married to a man who, though uniformly unsuccessful in his
hunting trips, boastingly spoke of his “killings.”
One day, returning from a trip, with the usual accompaniment of an
empty bag, it occurred to him that his wife would make fun of him if
he returned without even one proof of his oft-boasted skill. So he
purchased a brace of partridges to deceive his trusting spouse. As he
threw them on the table in front of her, he observed: “Well, my dear,
you see I am not so awkward with the gun after all.”
“Dick,” replied the wife, turning from the birds with a grimace, after
a brief examination, “you were quite right in shooting these birds to-
day; to-morrow it would have been too late.”
Uncle Toby was aghast at finding a strange darky with his arm
around Mandy’s waist.
“Mandy, tell dat niggah to take his ahm ’way from round yo’ waist,”
he indignantly commanded. “Tell him yo’self,” said Mandy haughtily.
“He’s a puffect stranger to me.”
A Cockney tourist was on a visit to a Highland town famous for its
golf-links. Through wearing a pair of stiff leather gaiters several sizes
too large for him, he was compelled to walk bow-legged. Being a
very slow player, others were forced to wait for him at every hole. At
the fourth hole a Highlander after watching the visitor miss the ball
three times was unable to wait any longer, and drove his ball clean
between the tourist’s legs. “What!” he of the gaitered legs yelled
furiously. “Do you call that golf?” “Mebbe no,” replied the Gael, “but
it’s very good croquet.”
After the sermon on Sunday morning the rector welcomed and
shook hands with a young German.
“And are you a regular communicant?” said the rector.
“Yes,” said the German, “I take the 7.45 every morning.”
Meeting a negro, a certain Southern gentleman asked him how he
was getting on.
The negro assumed a troubled look, and replied:
“Oh, so far’s physicality goes, I’m all right; but I sure do have ma
troubles wif ma wife.”
“Well, Sam, I’m sorry to hear that. What seems to be the matter?”
“She thinks money grows on trees, I reckon. All de time she keeps
pesterin’ me foh pinch o’ change. If it ain’t a dollah it’s half or a
quarter she wants.”
“What on earth does she do with the money?”
“I dunno. Ain’t nevah give her none yet.”
A mountaineer of one of the back counties of North Carolina was
arraigned with several others for illicit distilling. “Defendant,” said the
court, “what is your name?”
“Joshua,” was the reply.
“Are you the man who made the sun stand still?”
Quick as a flash came the answer, “No, sir; I am the man who made
the moonshine.”
“They thought more of the Legion of Honor in the time of the first
Napoleon than they do now,” said a well-known Frenchman. “The
emperor one day met an old one-armed veteran.
“‘How did you lose your arm?’ he asked.
“‘Sire, at Austerlitz.’
“‘And were you not decorated?’
“‘No, sire.’
“‘Then here is my own cross for you; I make you chevalier.’
“‘Your Majesty names me chevalier because I have lost one arm!
What would your Majesty have done had I lost both arms?’
“‘Oh, in that case I should have made you Officer of the Legion.’
“Whereupon the old soldier immediately drew his sword and cut off
his other arm.”
There is no particular reason to doubt this story. The only question
is, how did he do it?
A stranger in Boston was interested to discover, when dining with
friends once, that the dessert he would have classed as cream layer
cake at home was known in Boston as “Washington pie.” And the
next time he lunched at a restaurant, he ordered the same thing;
but the waiter put before him a rather heavy looking square of cake
covered with chocolate, instead of the cream cake the guest had
made up his mind to enjoy. A puzzled expression came over his face
as he said reprovingly, “I ordered Washington pie, waiter.”
“That is Washington pie, sir.”
“Well,” expostulated the disappointed man, “I did not mean Booker
T.—I want George!”
George Ade, automobiling in Indiana, dined at a country hotel
among a roomful of ministers.
The ministers, who were holding a convention in the town, were
much amused when Mr. Ade’s identity was disclosed to them.
One of them said during dinner:
“How does a humorist of your stamp feel, sir, in such reverend
company as this?”
“I feel,” said Mr. Ade promptly, “like a lion in a den of Daniels.”
It was a crowded tram car. Among those who could not find seats
was a young lady. Close to where she stood an old man was sitting.
He struggled as if to rise. The young woman cast a glance of scorn
at one or two men hiding behind newspapers. “Please don’t get up,”
she said to the old man, “I beg you won’t.” The conductor rang the
bell and the car went on. The old man’s features worked convulsively
and he mopped his face with his handkerchief. At the next stopping
place he again tried to rise and again the young woman tried to stop
him. “I would much rather stand,” she said, continuing to block his
way. “I don’t care whether you would or not,” said the old man,
crimson with fury, “I want to get out. You’ve made me come half a
mile too far already. Here, you, stop the car.” But it was too late, the
bell had already rung and he had to wait until the next stopping
place was reached.
“I want some cigars for my husband for Christmas.”
“What kind, madam?”
“Well, I don’t know, exactly; but he is a middle-aged man and
always dresses in black.”
John D. Rockefeller, Jr., tells a story of his father:
“Father tells many stories. Sometimes he tells a new one. Not long
ago he related one to me that concerned a man who had imbibed
rather too freely. The man, in this condition, fell into a watering
trough. To the officer who came to help him out as he wallowed in
the water, he said:
“‘Offzer, I ken save self. You save women an’ shildern.’”
“On Sunday, September 20, the wife of —— of a daughter. Others
please copy.”
Bret Harte was so frequently complimented as the author of “Little
Breeches” that he was almost as sorry it was ever written as was
Colonel John Hay, who preferred his fame to rest on more ambitious
works. A gushing lady who prided herself upon her literary tastes,
said to him once: “My dear Mr. Harte, I am so delighted to meet you.
I have read everything you ever wrote, but of all your dialect verse
there is none that compares to your ‘Little Breeches.’”
“I quite agree with you, madam,” said Mr. Harte, “but you have put
the little breeches on the wrong man.”
Mr. Knox, the Secretary of State in Taft’s Cabinet, was formerly
engaged in the practise of law in Pittsburg.
One day, says a friend, Mr. Knox was much put out to find on his
arrival at his office that everything was topsy-turvy and that the
temperature of his rooms was much too low for comfort.
Summoning his office-boy, a lad but recently entered his employ, the
lawyer asked who had raised every window in the place on such a
cold morning.
“Mr. Muldoon, sir,” was the answer.
“Who is Mr. Muldoon?” asked the attorney.
“The janitor, sir.”
“Who carried off my waste-basket?” was the next question.
“Mr. Reilly, sir.”
“And who is Mr. Reilly?”
“He’s the man that cleans the rooms.”
Mr. Knox looked sternly at the boy and said: “See here, Richard, we
call men by their first names here. We don’t ‘mister’ them in this
office. Do you understand?”
“Yes, sir.” And the boy retired.
In a few minutes he reappeared and in a shrill, piping voice
announced:
“There’s a gentleman that wants to see you, Philander.”
A Scottish parson, still on the under side of forty, was driving home
from an outlying hamlet when he overtook a young woman. He
recognized her as the maid of all work at a farm which he would
pass, so he pulled up and offered her a lift. Mary gladly accepted his
offer and they chatted pleasantly all the way to the farm gate.
“Thank you, sir,” she said as she got down.
“Don’t mention it, Mary. Don’t mention it,” he told her politely.
“No, I won’t,” Mary obligingly assured him.
A little girl was shown her newly-arrived baby brother. Looking at
him lovingly she said, “When will he talk, mother?” “Oh not for a
long time yet,” said the mother. “Yes, but when?” persisted the child.
“Well, not for a year or so.” After thinking for minute the child
exclaimed, “How funny. Miss Clark read out of the Bible this morning
that Job cursed the hour he was born.”
W. A. Sponsler, when in the Pennsylvania State Legislature, was
given to the making of very elaborate and florid speeches, and one
day brought an address to a close with “Vox populi, vox Dei.”
“I’ll bet you don’t know the meaning of what Sponsler just said,” said
Al Crawford to Hugh E. Mackin.
“I don’t know!” replied Mackin, indignantly. “Of course, I know!”
“You don’t know for ten dollars!” suggested Crawford.
Mackin, still indignant, posted his part of the wager with another
member of the Legislature, and Crawford said tauntingly:
“Well, now, tell us, what does it mean?”
“Vox populi, vox Dei,” quoted Mackin, solemnly, “as everybody
knows, is French for ‘My God! why hast thou forsaken me?’”
“Give him the money,” said Crawford. “Darned if he don’t know after
all!”
There is an old lady living in a small town in southern Pennsylvania
who makes great efforts to keep abreast of the times. Her
opportunities, however, are circumscribed, and she is sometimes
compelled to resort to her imagination. She went to a church
sociable lately, and as she entered the room one of the attendants
said:
“Good evening, auntie. I am glad you came. We are going to have
tableaux this evening.”
“Yes, I know,” replied the old lady; “I smelt ’em when I first came
in.”
Fifer was a dog of friendly and social habits, but when he wandered
into the lecture-tent at a well-known New Thought summer school
and went to sleep between the chairs, he did a very foolish thing. A
woman coming in poked him in the ribs with her parasol, startling
him from his peaceful dreams, and he sprang upon her with a
savage bite. A man grabbed him and he grabbed the man. The
excitement was intense when an earnest little woman standing on a
chair cried, “Some one hold the Thought!” “Hang the Thought!”
shouted a man in the rear. “Some one hold the dog!”
The boy was going away to school, full of high hope.
“I shall make the football team and color two pipes the first year!”
he said bravely.
His mother kissed him and wept. His father wrung his hand in
silence.
They were too full for speech then.
But when he was gone, and they were calmer, they talked together
of him, and prayed his ambition might not carry him beyond his
strength.
The car was entirely empty with the exception of one man, but as I
entered he rose, made me an unsteady but magnificent bow, and
said: “Madam, pleashe be kind ’nough to asshept thish plashe.”
There was nothing else for me to do, so I thanked him and sat
down. And for twenty blocks that idiot hung from a strap, swaying in
the breeze, with not a soul in the car but ourselves. Occasionally I
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

More Related Content

PDF
(Ebook) Android Cookbook by Ian F. Darwin ISBN 9781449374457, 144937445X
PDF
(Ebook) Android Cookbook by Ian F. Darwin ISBN 9781449374457, 144937445X
PDF
Android Cookbook Problems And Solutions For Android Developers Darwin
PDF
Android Cookbook 1st Edition Ian F. Darwin
PDF
Android Cookbook Early Release Ian F Darwin
PDF
iOS 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
PDF
Learning Swift 3 Early release 3rd Edition Jonathan Manning
PDF
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
(Ebook) Android Cookbook by Ian F. Darwin ISBN 9781449374457, 144937445X
(Ebook) Android Cookbook by Ian F. Darwin ISBN 9781449374457, 144937445X
Android Cookbook Problems And Solutions For Android Developers Darwin
Android Cookbook 1st Edition Ian F. Darwin
Android Cookbook Early Release Ian F Darwin
iOS 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
Learning Swift 3 Early release 3rd Edition Jonathan Manning
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...

Similar to Android Cookbook 2nd [early release] Edition Ian F. Darwin (20)

PDF
Developing Android Applications with Adobe AIR 1st Edition Véronique Brossier
PDF
iOS 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
PDF
Mobile app development with Ionic cross platform apps with Ionic Angular and ...
PDF
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
PDF
Mobile App Development With Ionic Crossplatform Apps With Ionic Angular And C...
PDF
Developing Android Applications with Adobe AIR 1st Edition Véronique Brossier
PDF
iOS 5 Programming Cookbook Solutions Examples for iPhone iPad and iPod touch ...
PDF
Learning Android 1st Edition Marko Gargenta
PDF
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning 2024 scribd...
PDF
Android Application Development Programming With The Google Sdk 1st Edition R...
PDF
iOS 5 Programming Cookbook Solutions Examples for iPhone iPad and iPod touch ...
PDF
Ios 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
PDF
iOS 5 Programming Cookbook Solutions Examples for iPhone iPad and iPod touch ...
PDF
Learning Swift 3 Early release 3rd Edition Jonathan Manning
PDF
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning
PDF
Learning Android 1st Edition Marko Gargenta
PDF
Learning React Native Building Native Mobile Apps With Javascript 2nd Edition...
PDF
Programming Windows Store Apps with C 1st Edition Matthew Baxter-Reynolds
PDF
iOS 7 in Action 1st Edition Brendan G. Lim
PDF
Learning the iPhone SDK for JavaScript Programmers Create Native Apps with Ob...
Developing Android Applications with Adobe AIR 1st Edition Véronique Brossier
iOS 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
Mobile app development with Ionic cross platform apps with Ionic Angular and ...
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
Mobile App Development With Ionic Crossplatform Apps With Ionic Angular And C...
Developing Android Applications with Adobe AIR 1st Edition Véronique Brossier
iOS 5 Programming Cookbook Solutions Examples for iPhone iPad and iPod touch ...
Learning Android 1st Edition Marko Gargenta
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning 2024 scribd...
Android Application Development Programming With The Google Sdk 1st Edition R...
iOS 5 Programming Cookbook Solutions Examples for iPhone iPad and iPod touch ...
Ios 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
iOS 5 Programming Cookbook Solutions Examples for iPhone iPad and iPod touch ...
Learning Swift 3 Early release 3rd Edition Jonathan Manning
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning
Learning Android 1st Edition Marko Gargenta
Learning React Native Building Native Mobile Apps With Javascript 2nd Edition...
Programming Windows Store Apps with C 1st Edition Matthew Baxter-Reynolds
iOS 7 in Action 1st Edition Brendan G. Lim
Learning the iPhone SDK for JavaScript Programmers Create Native Apps with Ob...
Ad

Recently uploaded (20)

PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
RMMM.pdf make it easy to upload and study
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
Pre independence Education in Inndia.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Lesson notes of climatology university.
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Insiders guide to clinical Medicine.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
RMMM.pdf make it easy to upload and study
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Basic Mud Logging Guide for educational purpose
Pre independence Education in Inndia.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPH.pptx obstetrics and gynecology in nursing
Lesson notes of climatology university.
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
O7-L3 Supply Chain Operations - ICLT Program
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Insiders guide to clinical Medicine.pdf
Microbial disease of the cardiovascular and lymphatic systems
O5-L3 Freight Transport Ops (International) V1.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
TR - Agricultural Crops Production NC III.pdf
Final Presentation General Medicine 03-08-2024.pptx
Module 4: Burden of Disease Tutorial Slides S2 2025
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Ad

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

  • 1. Android Cookbook 2nd [early release] Edition Ian F. Darwin download https://ebookname.com/product/android-cookbook-2nd-early-release- edition-ian-f-darwin/ Get Instant Ebook Downloads – Browse at https://ebookname.com
  • 2. 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/
  • 3. 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/
  • 4. 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/
  • 8. 978-1-449-37445-7 [FILL IN] 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 Production Editor: FILL IN PRODUCTION EDI‐ TOR Copyeditor: FILL IN COPYEDITOR Proofreader: FILL IN PROOFREADER Indexer: FILL IN INDEXER Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest 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.
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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
  • 13. 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…
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. 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
  • 20. 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
  • 21. 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
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. 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 Number API Level Name Datea Major Change / Notes CM Version 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 KitKat chocolate bar) 11 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
  • 29. 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
  • 30. Another Random Document on Scribd Without Any Related Topics
  • 34. The Project Gutenberg eBook of Among the Humorists and After Dinner Speakers, Vol. 1
  • 35. This ebook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this ebook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook. Title: Among the Humorists and After Dinner Speakers, Vol. 1 Editor: William Patten Release date: October 31, 2012 [eBook #41249] Most recently updated: October 23, 2024 Language: English Credits: Produced by D Alexander, Matthew Wheaton and the Online Distributed Proofreading Team at http://www.pgdp.net *** START OF THE PROJECT GUTENBERG EBOOK AMONG THE HUMORISTS AND AFTER DINNER SPEAKERS, VOL. 1 ***
  • 36. AMONG the HUMORISTS and AFTER DINNER SPEAKERS
  • 38. AMONG THE HUMORISTS AND AFTER-DINNER SPEAKERS
  • 39. A NEW COLLECTION OF HUMOROUS STORIES AND ANECDOTES SELECTED AND ARRANGED BY WILLIAM PATTEN Editor of American Short Story Classics, Foreign Short Story Classics, etc. VOL. I P. F. COLLIER & SON NEW YORK Copyright 1909 By P. F. Collier & Son
  • 40. PARTIAL LIST OF THE NAMES OF STORY-TELLERS IN THIS VOLUME George Ade Sir Wilfrid Laurier Bret Harte Oliver Herford Mark Twain J. M. Barrie Sec. of State P. C. Knox Richard Mansfield W. M. Evarts John Sharp Williams De Wolf Hopper J. G. Blaine King Edward of England Phillips Brooks Joseph Jefferson Daniel J. Sully Lord Beaconsfield Bill Nye Abraham Lincoln John C. Spooner Alvey A. Adee Robert Edeson Patrick A. Collins Andrew Lang Horace T. Eastman Benjamin R. Tillman D. G. Rossetti William E. Gladstone J. M. Maclaren Charles Lamb Dean Swift Edwin Booth Clyde Fitch Weedon Grossmith J. McNeill Whistler Senator W. A. Clark Leigh Hunt Francis Wilson Edward Everett Hale Chauncey M. Depew Dean Hole Albert J. Beveridge Irving Bacheller Beerbohm Tree Thomas B. Reed Herbert S. Stone J. C. S. Blackburn Frank R. Stockton N. C. Goodwin Henry James Brander Matthews William Allen White
  • 41. Andrew Carnegie Bishop Brewster Speaker Cannon Frederic Remington Walter Damrosch Julian Ralph Rev. Robert Collyer Senator John T. Morgan Rev. Sam Jones J. J. Ingalls Dean Kirchwey Archbishop Ryan John Wanamaker J. A. Tawney Henry Guy Carleton Thos. Bailey Aldrich Charles Francis Adams Elihu Root
  • 42. T PREFACE HE collection of these humorous paragraphs has extended over a number of years. Even a small beginning became a source of such entertainment that the collection grew and grew, always without any thought of publication. The man who can not laugh has yet to be found. Therein lies that immediate appeal to a common ground which the sense of humor gives, and it has been a conspicuous characteristic of those who look to the public for appreciation and support. Lord Palmerston and Abraham Lincoln were two notable examples of men for whom sympathy quickened through their ready wit, and no political speaker drives home his arguments half so well as he who can introduce a witty illustration. The joke has ever been a potent factor in combating oppression and corruption, in ridiculing shams. It has embalmed some reputations, and has blasted others. It is the champion of the weak against the strong, and has often illuminated for us, as in a flash, a glimpse of character or custom that would otherwise have been lost to the world. There is only one similar collection of which I am aware, the “Jest Book” by Mark Lemon, who was for twenty-nine years the editor of “Punch.” Alas that there should be fashions in jokes as well as in hats, for much of his book that we know must have been humorous reading to his contemporaries, leaves us, of the present generation in America, indifferent. I shall be glad if some of my readers are minded to do a graceful act and send me, in return, some paragraphs to add to my collection. I wish to take this opportunity to thank the following publications for the paragraphs borrowed from their columns:
  • 43. Evening Sun, Lippincott’s, Pittsburg Dispatch, San Francisco News- Letter, Ladies’ Home Journal, Washington Star, Mail and Express, Youth’s Companion, Life, Good Housekeeping, Argonaut, Buffalo Commercial, Tit-Bits, Punch, The Tattler, Harper’s Weekly, Harper’s Monthly, Democratic Telegram, Cleveland Plaindealer, Harvard Lampoon, Judge, Philadelphia Ledger, Saturday Evening Post, Philadelphia Evening Bulletin, Boston Herald, Kansas City Star, Washington Post, Success, Atchison Globe, New York Times, Woman’s Home Companion, London Mail, Louisville Courier-Journal, Rochester Post-Express, New York Tribune, New York Observer, Chicago Daily News, Pittsburg Post, Pittsburg Observer, Philadelphia Public Ledger, New York World, Pick-me-up, Harper’s Bazar, The Green Bag, Tacoma Ledger, Pittsburg Dispatch, The Wasp, Cornell Widow, Washington Post, Kansas City Independent, Short Stories. W. P.
  • 44. T AMONG THE HUMORISTS AND AFTER-DINNER SPEAKERS HERE is a delicious flavor about this story of a Virginia lady, married to a man who, though uniformly unsuccessful in his hunting trips, boastingly spoke of his “killings.” One day, returning from a trip, with the usual accompaniment of an empty bag, it occurred to him that his wife would make fun of him if he returned without even one proof of his oft-boasted skill. So he purchased a brace of partridges to deceive his trusting spouse. As he threw them on the table in front of her, he observed: “Well, my dear, you see I am not so awkward with the gun after all.” “Dick,” replied the wife, turning from the birds with a grimace, after a brief examination, “you were quite right in shooting these birds to- day; to-morrow it would have been too late.” Uncle Toby was aghast at finding a strange darky with his arm around Mandy’s waist. “Mandy, tell dat niggah to take his ahm ’way from round yo’ waist,” he indignantly commanded. “Tell him yo’self,” said Mandy haughtily. “He’s a puffect stranger to me.” A Cockney tourist was on a visit to a Highland town famous for its golf-links. Through wearing a pair of stiff leather gaiters several sizes too large for him, he was compelled to walk bow-legged. Being a
  • 45. very slow player, others were forced to wait for him at every hole. At the fourth hole a Highlander after watching the visitor miss the ball three times was unable to wait any longer, and drove his ball clean between the tourist’s legs. “What!” he of the gaitered legs yelled furiously. “Do you call that golf?” “Mebbe no,” replied the Gael, “but it’s very good croquet.” After the sermon on Sunday morning the rector welcomed and shook hands with a young German. “And are you a regular communicant?” said the rector. “Yes,” said the German, “I take the 7.45 every morning.” Meeting a negro, a certain Southern gentleman asked him how he was getting on. The negro assumed a troubled look, and replied: “Oh, so far’s physicality goes, I’m all right; but I sure do have ma troubles wif ma wife.” “Well, Sam, I’m sorry to hear that. What seems to be the matter?” “She thinks money grows on trees, I reckon. All de time she keeps pesterin’ me foh pinch o’ change. If it ain’t a dollah it’s half or a quarter she wants.” “What on earth does she do with the money?” “I dunno. Ain’t nevah give her none yet.”
  • 46. A mountaineer of one of the back counties of North Carolina was arraigned with several others for illicit distilling. “Defendant,” said the court, “what is your name?” “Joshua,” was the reply. “Are you the man who made the sun stand still?” Quick as a flash came the answer, “No, sir; I am the man who made the moonshine.” “They thought more of the Legion of Honor in the time of the first Napoleon than they do now,” said a well-known Frenchman. “The emperor one day met an old one-armed veteran. “‘How did you lose your arm?’ he asked. “‘Sire, at Austerlitz.’ “‘And were you not decorated?’ “‘No, sire.’ “‘Then here is my own cross for you; I make you chevalier.’ “‘Your Majesty names me chevalier because I have lost one arm! What would your Majesty have done had I lost both arms?’ “‘Oh, in that case I should have made you Officer of the Legion.’ “Whereupon the old soldier immediately drew his sword and cut off his other arm.” There is no particular reason to doubt this story. The only question is, how did he do it?
  • 47. A stranger in Boston was interested to discover, when dining with friends once, that the dessert he would have classed as cream layer cake at home was known in Boston as “Washington pie.” And the next time he lunched at a restaurant, he ordered the same thing; but the waiter put before him a rather heavy looking square of cake covered with chocolate, instead of the cream cake the guest had made up his mind to enjoy. A puzzled expression came over his face as he said reprovingly, “I ordered Washington pie, waiter.” “That is Washington pie, sir.” “Well,” expostulated the disappointed man, “I did not mean Booker T.—I want George!” George Ade, automobiling in Indiana, dined at a country hotel among a roomful of ministers. The ministers, who were holding a convention in the town, were much amused when Mr. Ade’s identity was disclosed to them. One of them said during dinner: “How does a humorist of your stamp feel, sir, in such reverend company as this?” “I feel,” said Mr. Ade promptly, “like a lion in a den of Daniels.” It was a crowded tram car. Among those who could not find seats was a young lady. Close to where she stood an old man was sitting. He struggled as if to rise. The young woman cast a glance of scorn at one or two men hiding behind newspapers. “Please don’t get up,” she said to the old man, “I beg you won’t.” The conductor rang the bell and the car went on. The old man’s features worked convulsively
  • 48. and he mopped his face with his handkerchief. At the next stopping place he again tried to rise and again the young woman tried to stop him. “I would much rather stand,” she said, continuing to block his way. “I don’t care whether you would or not,” said the old man, crimson with fury, “I want to get out. You’ve made me come half a mile too far already. Here, you, stop the car.” But it was too late, the bell had already rung and he had to wait until the next stopping place was reached. “I want some cigars for my husband for Christmas.” “What kind, madam?” “Well, I don’t know, exactly; but he is a middle-aged man and always dresses in black.” John D. Rockefeller, Jr., tells a story of his father: “Father tells many stories. Sometimes he tells a new one. Not long ago he related one to me that concerned a man who had imbibed rather too freely. The man, in this condition, fell into a watering trough. To the officer who came to help him out as he wallowed in the water, he said: “‘Offzer, I ken save self. You save women an’ shildern.’” “On Sunday, September 20, the wife of —— of a daughter. Others please copy.”
  • 49. Bret Harte was so frequently complimented as the author of “Little Breeches” that he was almost as sorry it was ever written as was Colonel John Hay, who preferred his fame to rest on more ambitious works. A gushing lady who prided herself upon her literary tastes, said to him once: “My dear Mr. Harte, I am so delighted to meet you. I have read everything you ever wrote, but of all your dialect verse there is none that compares to your ‘Little Breeches.’” “I quite agree with you, madam,” said Mr. Harte, “but you have put the little breeches on the wrong man.” Mr. Knox, the Secretary of State in Taft’s Cabinet, was formerly engaged in the practise of law in Pittsburg. One day, says a friend, Mr. Knox was much put out to find on his arrival at his office that everything was topsy-turvy and that the temperature of his rooms was much too low for comfort. Summoning his office-boy, a lad but recently entered his employ, the lawyer asked who had raised every window in the place on such a cold morning. “Mr. Muldoon, sir,” was the answer. “Who is Mr. Muldoon?” asked the attorney. “The janitor, sir.” “Who carried off my waste-basket?” was the next question. “Mr. Reilly, sir.” “And who is Mr. Reilly?” “He’s the man that cleans the rooms.” Mr. Knox looked sternly at the boy and said: “See here, Richard, we call men by their first names here. We don’t ‘mister’ them in this
  • 50. office. Do you understand?” “Yes, sir.” And the boy retired. In a few minutes he reappeared and in a shrill, piping voice announced: “There’s a gentleman that wants to see you, Philander.” A Scottish parson, still on the under side of forty, was driving home from an outlying hamlet when he overtook a young woman. He recognized her as the maid of all work at a farm which he would pass, so he pulled up and offered her a lift. Mary gladly accepted his offer and they chatted pleasantly all the way to the farm gate. “Thank you, sir,” she said as she got down. “Don’t mention it, Mary. Don’t mention it,” he told her politely. “No, I won’t,” Mary obligingly assured him. A little girl was shown her newly-arrived baby brother. Looking at him lovingly she said, “When will he talk, mother?” “Oh not for a long time yet,” said the mother. “Yes, but when?” persisted the child. “Well, not for a year or so.” After thinking for minute the child exclaimed, “How funny. Miss Clark read out of the Bible this morning that Job cursed the hour he was born.” W. A. Sponsler, when in the Pennsylvania State Legislature, was given to the making of very elaborate and florid speeches, and one
  • 51. day brought an address to a close with “Vox populi, vox Dei.” “I’ll bet you don’t know the meaning of what Sponsler just said,” said Al Crawford to Hugh E. Mackin. “I don’t know!” replied Mackin, indignantly. “Of course, I know!” “You don’t know for ten dollars!” suggested Crawford. Mackin, still indignant, posted his part of the wager with another member of the Legislature, and Crawford said tauntingly: “Well, now, tell us, what does it mean?” “Vox populi, vox Dei,” quoted Mackin, solemnly, “as everybody knows, is French for ‘My God! why hast thou forsaken me?’” “Give him the money,” said Crawford. “Darned if he don’t know after all!” There is an old lady living in a small town in southern Pennsylvania who makes great efforts to keep abreast of the times. Her opportunities, however, are circumscribed, and she is sometimes compelled to resort to her imagination. She went to a church sociable lately, and as she entered the room one of the attendants said: “Good evening, auntie. I am glad you came. We are going to have tableaux this evening.” “Yes, I know,” replied the old lady; “I smelt ’em when I first came in.”
  • 52. Fifer was a dog of friendly and social habits, but when he wandered into the lecture-tent at a well-known New Thought summer school and went to sleep between the chairs, he did a very foolish thing. A woman coming in poked him in the ribs with her parasol, startling him from his peaceful dreams, and he sprang upon her with a savage bite. A man grabbed him and he grabbed the man. The excitement was intense when an earnest little woman standing on a chair cried, “Some one hold the Thought!” “Hang the Thought!” shouted a man in the rear. “Some one hold the dog!” The boy was going away to school, full of high hope. “I shall make the football team and color two pipes the first year!” he said bravely. His mother kissed him and wept. His father wrung his hand in silence. They were too full for speech then. But when he was gone, and they were calmer, they talked together of him, and prayed his ambition might not carry him beyond his strength. The car was entirely empty with the exception of one man, but as I entered he rose, made me an unsteady but magnificent bow, and said: “Madam, pleashe be kind ’nough to asshept thish plashe.” There was nothing else for me to do, so I thanked him and sat down. And for twenty blocks that idiot hung from a strap, swaying in the breeze, with not a soul in the car but ourselves. Occasionally I
  • 53. 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