Android Cookbook Problems And Solutions For Android Developers Darwin
Android Cookbook Problems And Solutions For Android Developers Darwin
Android Cookbook Problems And Solutions For Android Developers Darwin
Android Cookbook Problems And Solutions For Android Developers Darwin
1. Android Cookbook Problems And Solutions For
Android Developers Darwin download
https://ebookbell.com/product/android-cookbook-problems-and-
solutions-for-android-developers-darwin-22049566
Explore and download more ebooks at ebookbell.com
2. Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Android Cookbook Problems And Solutions For Android Developers Ian F
Darwin Darwin
https://ebookbell.com/product/android-cookbook-problems-and-solutions-
for-android-developers-ian-f-darwin-darwin-23141286
Android 9 Development Cookbook Over 100 Recipes And Solutions To Solve
The Most Common Problems Faced By Android Developers 3rd Edition Boyer
https://ebookbell.com/product/android-9-development-cookbook-
over-100-recipes-and-solutions-to-solve-the-most-common-problems-
faced-by-android-developers-3rd-edition-boyer-38076050
Android 9 Development Cookbook Over 100 Recipes And Solutions To Solve
The Most Common Problems Faced By Android Developers 3rd Edition Rick
Boyer
https://ebookbell.com/product/android-9-development-cookbook-
over-100-recipes-and-solutions-to-solve-the-most-common-problems-
faced-by-android-developers-3rd-edition-rick-boyer-167751604
Android Application Development Cookbook 2nd Edition Over 100 Recipes
To Help You Solve The Most Common Problems Faced By Android Developers
Today Rick Boyer
https://ebookbell.com/product/android-application-development-
cookbook-2nd-edition-over-100-recipes-to-help-you-solve-the-most-
common-problems-faced-by-android-developers-today-rick-boyer-5476278
3. Android Cookbook 1st Edition Ian F Darwin
https://ebookbell.com/product/android-cookbook-1st-edition-ian-f-
darwin-2322658
Android Cookbook Early Release Ian F Darwin
https://ebookbell.com/product/android-cookbook-early-release-ian-f-
darwin-2476236
Android Cookbook 2nd Early Release Ian F Darwin
https://ebookbell.com/product/android-cookbook-2nd-early-release-ian-
f-darwin-5903428
Android Cookbook Ian F Darwin
https://ebookbell.com/product/android-cookbook-ian-f-darwin-53633048
Android Cookbook Ian F Darwin
https://ebookbell.com/product/android-cookbook-ian-f-darwin-53636366
9. 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…
11. Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
1. Getting Started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Understanding the Android Application Architecture 1
1.2 Understanding the Android Activity Life Cycle 3
1.3 Learning About Android Releases 5
1.4 Learning the Java Language 7
1.5 Creating a “Hello, World” Application from the Command Line 8
1.6 Creating a “Hello, World” App with Apache Maven 13
1.7 Choosing an IDE for Android Development 15
1.8 Setting Up Android Studio 18
1.9 Installing Platform Editions and Keeping the SDK Updated 21
1.10 Creating a “Hello, World” App Using Android Studio 25
1.11 Converting an Eclipse ADT Project to Android Studio 30
1.12 Preserving History While Converting from Eclipse to Android Studio 34
1.13 Building an Android Application with both Eclipse and Android Studio 36
1.14 Setting Up Eclipse with AndMore (Replacing ADT) 39
1.15 Creating a “Hello, World” Application Using Eclipse 46
1.16 Installing the Eclipse Marketplace Client in Your Eclipse 51
1.17 Upgrading a Project from Eclipse ADT to Eclipse AndMore 53
1.18 Controlling Emulators/Devices Using Command-Line ADB 57
1.19 Sharing Java Classes from Another Eclipse Project 59
1.20 Referencing Libraries to Implement External Functionality 62
1.21 Using New Features on Old Devices via the Compatibility Libraries 67
1.22 Using SDK Samples to Help Avoid Head Scratching 68
1.23 Taking a Screenshot/Video from the Emulator/Android Device 70
1.24 Program: A Simple CountDownTimer Example 76
1.25 Program: Tipster, a Tip Calculator for the Android OS 79
v
12. 2. Designing a Successful Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
2.1 Exception Handling 101
2.2 Requesting Android Permissions at Runtime 104
2.3 Accessing Android’s Application Object as a “Singleton” 106
2.4 Keeping Data When the User Rotates the Device 109
2.5 Monitoring the Battery Level of an Android Device 111
2.6 Creating Splash Screens in Android 113
2.7 Designing a Conference/Camp/Hackathon/Institution App 117
2.8 Using Google Analytics in an Android Application 119
2.9 Setting First-Run Preferences 122
2.10 Formatting Numbers 123
2.11 Formatting with Correct Plurals 127
2.12 Formatting the Time and Date for Display 130
2.13 Simplifying Date/Time Calculations with the Java 8 java.time API 132
2.14 Controlling Input with KeyListeners 134
2.15 Backing Up Android Application Data 137
2.16 Using Hints Instead of Tool Tips 144
3. Application Testing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
3.1 Setting Up an Android Virtual Device (AVD) for App Testing 148
3.2 Testing on a Wide Range of Devices with Cloud-Based Testing 154
3.3 Testing with Eclipse and JUnit 155
3.4 Testing with Android Studio and JUnit 158
3.5 Testing with Robolectric and JUnit 4 163
3.6 Testing with ATSL, Espresso, and JUnit 4 166
3.7 Troubleshooting Application Crashes 170
3.8 Debugging Using Log.d() and LogCat 173
3.9 Getting Bug Reports Automatically with Crash Reporting 175
3.10 Using a Local Runtime Application Log for Analysis of Field Errors or
Situations 178
3.11 Reproducing Activity Life-Cycle Scenarios for Testing 181
3.12 Keeping Your App Snappy with StrictMode 186
3.13 Static Code Testing with Android Lint 187
3.14 Dynamic Testing with the Monkey Program 189
3.15 Sending Text Messages and Placing Calls Between AVDs 191
4. Inter-/Intra-Process Communication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
4.1 Opening a Web Page, Phone Number, or Anything Else with an Intent 194
4.2 Emailing Text from a View 196
4.3 Sending an Email with Attachments 199
4.4 Pushing String Values Using Intent.putExtra() 201
4.5 Retrieving Data from a Subactivity Back to Your Main Activity 202
vi | Table of Contents
13. 4.6 Keeping a Background Service Running While Other Apps Are on Display 205
4.7 Sending/Receiving a Broadcast Message 207
4.8 Starting a Service After Device Reboot 208
4.9 Creating a Responsive Application Using Threads 209
4.10 Using AsyncTask to Do Background Processing 210
4.11 Sending Messages Between Threads Using an Activity Thread Queue and
Handler 218
4.12 Creating an Android Epoch HTML/JavaScript Calendar 220
5. Graphics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
5.1 Using a Custom Font 227
5.2 Drawing a Spinning Cube with OpenGL ES 230
5.3 Adding Controls to the OpenGL Spinning Cube 234
5.4 Freehand Drawing Smooth Curves 237
5.5 Taking a Picture Using an Intent 242
5.6 Taking a Picture Using android.media.Camera 244
5.7 Scanning a Barcode or QR Code with the Google ZXing Barcode Scanner 248
5.8 Using AndroidPlot to Display Charts and Graphs 251
5.9 Using Inkscape to Create an Android Launcher Icon from
OpenClipArt.org 254
5.10 Using Paint.NET to Create Launcher Icons from OpenClipArt.org 259
5.11 Using Nine Patch Files 267
5.12 Creating HTML5 Charts with Android RGraph 270
5.13 Adding a Simple Raster Animation 274
5.14 Using Pinch to Zoom 278
6. Graphical User Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
6.1 Understanding and Following User Interface Guidelines 282
6.2 Looking Good with Material Design 283
6.3 Choosing a Layout Manager (a.k.a. ViewGroup) and Arranging
Components 287
6.4 Handling Configuration Changes by Decoupling the View from the Model 288
6.5 Controlling the Action Bar 291
6.6 Adding a Share Action to Your Action Bar 295
6.7 Building Modern UIs with the Fragment API 299
6.8 Creating a Button and Its Click Event Listener 304
6.9 Enhancing UI Design Using Image Buttons 305
6.10 Using a FloatingActionButton 306
6.11 Wiring Up an Event Listener in Many Different Ways 309
6.12 Using CheckBoxes and RadioButtons 314
6.13 Using Card Widgets 318
6.14 Offering a Drop-Down Chooser via the Spinner Class 320
Table of Contents | vii
14. 6.15 Handling Long-Press/Long-Click Events 323
6.16 Displaying Text Fields with TextView and EditText 324
6.17 Constraining EditText Values with Attributes and the TextWatcher
Interface 325
6.18 Implementing AutoCompleteTextView 328
6.19 Feeding AutoCompleteTextView Using a SQLite Database Query 330
6.20 Turning Edit Fields into Password Fields 332
6.21 Changing the Enter Key to “Next” on the Soft Keyboard 333
6.22 Processing Key-Press Events in an Activity 336
6.23 Let Them See Stars: Using RatingBar 337
6.24 Making a View Shake 341
6.25 Providing Haptic Feedback 342
6.26 Navigating Different Activities Within a TabView 346
6.27 Creating a Loading Screen that Will Appear Between Two Activities 347
6.28 Adding a Border with Rounded Corners to a Layout 349
6.29 Detecting Gestures in Android 351
6.30 Creating a Simple App Widget 358
7. GUI Alerts: Menus, Dialogs, Toasts, Snackbars, and Notifications. . . . . . . . . . . . . . . . . 363
7.1 Alerting the User with Toast and Snackbar 364
7.2 Customizing the Appearance of a Toast 366
7.3 Creating and Displaying a Menu 367
7.4 Handling Choice Selection in a Menu 369
7.5 Creating a Submenu 370
7.6 Creating a Pop-up/Alert Dialog 372
7.7 Using a Timepicker Widget 374
7.8 Creating an iPhone-like WheelPicker for Selection 376
7.9 Creating a Tabbed Dialog 379
7.10 Creating a ProgressDialog 382
7.11 Creating a Custom Dialog with Buttons, Images, and Text 383
7.12 Creating a Reusable “About Box” Class 385
7.13 Creating a Notification in the Status Bar 389
8. Other GUI Elements: Lists and Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
8.1 Building List-Based Applications with RecyclerView 395
8.2 Building List-Based Applications with ListView 399
8.3 Creating a “No Data” View for ListViews 403
8.4 Creating an Advanced ListView with Images and Text 405
8.5 Using Section Headers in ListViews 409
8.6 Keeping the ListView with the User’s Focus 413
8.7 Writing a Custom List Adapter 414
8.8 Using a SearchView to Search Through Data in a ListView 418
viii | Table of Contents
15. 8.9 Handling Orientation Changes: From ListView Data Values to Landscape
Charting 420
9. Multimedia. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
9.1 Playing a YouTube Video 425
9.2 Capturing Video Using MediaRecorder 426
9.3 Using Android’s Face Detection Capability 429
9.4 Playing Audio from a File 432
9.5 Playing Audio Without Interaction 435
9.6 Using Speech to Text 437
9.7 Making the Device Speak with Text-to-Speech 438
10. Data Persistence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
10.1 Reading and Writing Files in Internal and External Storage 442
10.2 Getting File and Directory Information 446
10.3 Reading a File Shipped with the App Rather than in the Filesystem 451
10.4 Getting Space Information About the SD Card 453
10.5 Providing a Preference Activity 454
10.6 Checking the Consistency of Default Shared Preferences 459
10.7 Using a SQLite Database in an Android Application 461
10.8 Performing Advanced Text Searches on a SQLite Database 464
10.9 Working with Dates in SQLite 470
10.10 Exposing Non-SQL Data as a SQL Cursor 472
10.11 Displaying Data with a CursorLoader 475
10.12 Parsing JSON Using JSONObject 478
10.13 Parsing an XML Document Using the DOM API 480
10.14 Storing and Retrieving Data via a Content Provider 482
10.15 Writing a Content Provider 483
10.16 Adding a Contact Through the Contacts Content Provider 487
10.17 Reading Contact Data Using a Content Provider 490
10.18 Implementing Drag and Drop 492
10.19 Sharing Files via a FileProvider 496
10.20 Backing Up Your SQLite Data to the Cloud with a SyncAdapter 501
10.21 Storing Data in the Cloud with Google Firebase 510
11. Telephone Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
11.1 Doing Something When the Phone Rings 517
11.2 Processing Outgoing Phone Calls 521
11.3 Dialing the Phone 525
11.4 Sending Single-part or Multipart SMS Messages 527
11.5 Receiving an SMS Message 529
11.6 Using Emulator Controls to Send SMS Messages to the Emulator 531
Table of Contents | ix
16. 11.7 Using Android’s TelephonyManager to Obtain Device Information 532
12. Networked Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
12.1 Consuming a RESTful Web Service Using a URLConnection 544
12.2 Consuming a RESTful Web Service with Volley 547
12.3 Notifying Your App with Google Cloud Messaging “Push Messaging” 549
12.4 Extracting Information from Unstructured Text Using Regular
Expressions 558
12.5 Parsing RSS/Atom Feeds Using ROME 559
12.6 Using MD5 to Digest Clear Text 564
12.7 Converting Text into Hyperlinks 565
12.8 Accessing a Web Page Using a WebView 566
12.9 Customizing a WebView 567
12.10 Writing an Inter-Process Communication Service 568
13. Gaming and Animation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
13.1 Building an Android Game Using flixel-gdx 576
13.2 Building an Android Game Using AndEngine 580
13.3 Processing Timed Keyboard Input 587
14. Social Networking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
14.1 Authenticating Users with OAUTH2 589
14.2 Integrating Social Networking Using HTTP 593
14.3 Loading a User’s Twitter Timeline Using HTML or JSON 596
15. Location and Map Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
15.1 Getting Location Information 599
15.2 Accessing GPS Information in Your Application 601
15.3 Mocking GPS Coordinates on a Device 603
15.4 Using Geocoding and Reverse Geocoding 606
15.5 Getting Ready for Google Maps API V2 Development 607
15.6 Using the Google Maps API V2 612
15.7 Displaying Map Data Using OpenStreetMap 618
15.8 Creating Overlays in OpenStreetMap Maps 621
15.9 Using a Scale on an OpenStreetMap Map 623
15.10 Handling Touch Events on an OpenStreetMap Overlay 624
15.11 Getting Location Updates with OpenStreetMap Maps 627
16. Accelerometer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
16.1 Checking for the Presence or Absence of a Sensor 631
16.2 Using the Accelerometer to Detect Shaking 632
16.3 Checking Whether a Device Is Facing Up or Down 636
x | Table of Contents
17. 16.4 Reading the Temperature Sensor 637
17. Bluetooth. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639
17.1 Enabling Bluetooth and Making the Device Discoverable 639
17.2 Connecting to a Bluetooth-Enabled Device 641
17.3 Accepting Connections from a Bluetooth Device 644
17.4 Implementing Bluetooth Device Discovery 645
18. System and Device Control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
18.1 Accessing Phone Network/Connectivity Information 647
18.2 Obtaining Information from the Manifest File 648
18.3 Changing Incoming Call Notification to Silent, Vibrate, or Normal 649
18.4 Copying Text and Getting Text from the Clipboard 652
18.5 Using LED-Based Notifications 652
18.6 Making the Device Vibrate 653
18.7 Determining Whether a Given Application Is Running 654
19. All the World’s Not Java: Other Programming Languages and Frameworks. . . . . . . . . 657
19.1 Learning About Cross-Platform Solutions 658
19.2 Running Shell Commands from Your Application 659
19.3 Running Native C/C++ Code with JNI on the NDK 661
19.4 Getting Started with SL4A, the Scripting Layer for Android 667
19.5 Creating Alerts in SL4A 669
19.6 Fetching Your Google Documents and Displaying Them in a ListView
Using SL4A 673
19.7 Sharing SL4A Scripts in QR Codes 676
19.8 Using Native Handset Functionality from a WebView via JavaScript 678
19.9 Building a Cross-Platform App with Xamarin 680
19.10 Creating a Cross-Platform App Using PhoneGap/Cordova 685
20. All the World’s Not English: Strings and Internationalization. . . . . . . . . . . . . . . . . . . . 689
20.1 Internationalizing Application Text 690
20.2 Finding and Translating Strings 693
20.3 Handling the Nuances of strings.xml 695
21. Packaging, Deploying, and Distributing/Selling Your App. . . . . . . . . . . . . . . . . . . . . . . 701
21.1 Creating a Signing Certificate and Using It to Sign Your Application 701
21.2 Distributing Your Application via the Google Play Store 705
21.3 Distributing Your Application via Other App Stores 707
21.4 Monetizing Your App with AdMob 708
21.5 Obfuscating and Optimizing with ProGuard 714
21.6 Hosting Your App on Your Own Server 717
Table of Contents | xi
18. 21.7 Creating a “Self-Updating” App 718
21.8 Providing a Link to Other Published Apps in the Google Play Store 720
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725
xii | Table of Contents
19. Preface
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 Neo FreeRunner to QT Embedded, Moblin, LiMo, Debian Mobile,
Maemo, Firefox OS, and Ubuntu Mobile to the open sourced Symbian OS and the
now-defunct HP WebOS. And let’s not forget the established closed source stalwart,
Apple’s iOS, and the two minor players (by market share), Microsoft’s Windows
Phone, and the now-abandoned BlackBerry OS 10.
Amongst all these offerings, two stand out as major players. Android is definitely
here to stay! Due to its open source licensing, Android is used on many economy-
model phones around the world, and indeed, Android has been estimated to be on as
many as 90% of the world’s smartphones. 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, the reliability and portability of a standard high-level lan‐
guage 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), com‐
piled 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‐
tion that all current BlackBerry devices can run Android applications, and, in fact,
xiii
20. before it outsourced the remains of its smartphone business, BlackBerry’s last devices
only ran Android.
It’s now generally believed that Android has almost three-quarters of the world
smartphone market, although it has not 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.
Android is also available for several specialized platforms. Android Wear brings
Android’s programming model to the smartwatch and wearable environment for uses
such as fitness trackers. Android Auto is designed for controlling the entertainment
units in automobiles. Android TV runs in smart TVs and controllers for not-so-
smart TVs. Finally, Android Things is designed for the embedded market, now
known as “the internet of things” (IoT). Each of these platforms is fascinating, but to
keep the book to a reasonable size, we focus primarily on “regular Android,” Android
for smartphone and tablet applications.
Who This Book Is By
This book was co-written by several dozen Android developers from the Android
community at large. Development occurred in the open, on the Android Cookbook
website, 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 xxi. I am deeply grateful to all the con‐
tributors, who have helped move this book from a dream to the reality that you have
in your hands (or onscreen if you are reading the ebook format). Thank you all!
Who This Book Is For
This book focuses 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 Recipe 19.10), but it will be difficult to get the all-important 100%-
correct user experience 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 Samples associated with the Android SDK in that it tries to
focus more on how a given piece of technology works, rather than giving you (as
many of the Samples do) a complete, working example that has both been simplified
xiv | Preface
21. (to use very simple data) and 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.
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 and across
applications. In Chapter 4 we discuss Intents and broadcast receivers, Services,
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.
Chapter 7 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. Chapter 8
focuses on the “list” components in Android: the ListView and its newer replacement,
the RecyclerView.
Android is rich in multimedia capabilities. Chapter 9 shows how to use the most
important of these.
Chapter 10 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 a SQL database. This chapter also shows
you how to make application data available to other applications through something
Preface | xv
22. 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. Chapter 11 shows
how to control and react to the telephony component 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. Chapter 12 shows the
coding for traditional networked applications. This is followed by Chapter 13, which
discusses gaming and animation, and Chapter 14, which discusses social networking.
The now-ubiquitous Global Positioning System (GPS) has also had a major impact
on how mobile applications work. Chapter 15 discusses how to find a device’s loca‐
tion, how to get map data from Google and OpenStreetMap, and how applications
can be location-aware in ways that are just now being explored.
Chapter 16 talks about the sensors built into most Android devices and how to use
them.
Chapter 17 talks about the low-energy very-local area networking that Bluetooth ena‐
bles, 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 Chapter 18. Because Android is Linux-based, a
few of the recipes in this chapter deal with traditional Unix/Linux commands and
facilities.
In Chapter 19, 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 lan‐
guages.
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. Chapter 20 goes over the issues of language and
culture and how they relate to Android.
xvi | Preface
23. Finally, most Android developers hope other people will use their applications. But
this won’t happen if users can’t find the applications. Chapter 21 shows how to pre‐
pare your application for distribution via the Google Play Store, and to use that as
well as other markets to get your application out to the people who will use it.
Content Updates—Second Edition, March 2017
Major revision for Android Nougat (7.x). As befits a major revision, there are numer‐
ous new recipes to cover all the APIs that have been added or replaced over the past
several releases of Android. Of necessity, a few older recipes were retired. Some rec‐
ipes were moved around, which resulted in renumbering of most of the chapters.
The Android O Preview was released in the final week of this edition’s proofing stage,
and a few references are made to Android O; these should be regarded as “forward-
looking statements,” as “O” is still in a preview release.
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.
This element signifies a tip or suggestion.
This element signifies a general note.
Preface | xvii
24. This element signifies a warning or caution.
And here is our first warning: 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 repos‐
itory 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.
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 as hyperlinks
for ebook users to download from at the end of each recipe. In each case the archive
file is expected to contain a complete Eclipse or Android Studio project. We have no
control over these other repositories, so if one of them is incomplete, or stops work‐
ing, please refer to the GitHub repository instead.
Almost all code examples originally written for Eclipse now also
contain a build.gradle file so they can be opened directly in
Android Studio as well (see Recipe 1.12 to see how we did this).
Code examples originally written for Android Studio can, in gen‐
eral, not be used by Eclipse without reorganizing the project struc‐
ture.
xviii | Preface
25. How to Determine How a Project Can Be Built
If a project’s top-level directory contains:
AndroidManifest.xml and .project
It is openable with Eclipse.
build.gradle
It is openable with Android Studio or buildable with
command-line Gradle.
pom.xml
It is buildable with command-line Maven (or using Maven
inside an IDE).
build.xml
It might still be buildable with the older Ant build tool.
See Figure P-1 for an example of a typical project layout.
The top level of the Git repository for the examples contains a
README file, viewable below the list of files and directories, which
summarizes which projects can be built using which tools. Please
pay attention to the Notes column, as there may at any time be
some known issues with building the examples.
Figure P-1. Project layout for typical Eclipse and Studio projects
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
Preface | xix
26. 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
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, Second Edi‐
tion, by Ian F. Darwin (O’Reilly). Copyright 2017 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.
O’Reilly Safari
Safari (formerly Safari Books Online) is a membership-based
training and reference platform for enterprise, government,
educators, and individuals.
Members have access to thousands of books, training videos, Learning Paths, interac‐
tive tutorials, and curated playlists from over 250 publishers, including O’Reilly
Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Profes‐
sional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press,
John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe
Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, and
Course Technology, among others.
For more information, please visit http://oreilly.com/safari.
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)
xx | Preface
27. We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://bit.ly/android-cookbook-2e.
To comment or ask technical questions about this book, send email to bookques‐
tions@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: https://facebook.com/oreilly
Follow us on Twitter: https://twitter.com/oreillymedia
Watch us on YouTube: https://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, Wagied Davids,
Nidhin Jose Davis, David Dawes, Enrique Diaz, Marco Dinacci, Claudio Esperanca,
Kurosh Fallahzadeh, Daniel Fowler, Jonathan Fuerth, Sunit Katkar, Roger Kind Kris‐
tiansen, Vladimir Kroz, Alex Leffelman, Ulysses Levy, Thomas Manthey, Emaad
Manzoor, Zigurd Mednieks, Keith Mendoza, Roberto Calvo Palomino, Federico Pao‐
linelli, 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
second edition, and Daniel Fowler for updating several of his recipes for this 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 copyeditor 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! For
the second edition: Colleen Lobner, Kim Cofer, Rachel Head, and Judith McConville.
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.
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
Preface | xxi
28. ones that doubtless remain. Not only that, they both came back for the second edi‐
tion! 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!
xxii | Preface
29. CHAPTER 1
Getting Started
The famous “Hello, World” pattern came about back in 1978 when Brian Kernighan
and P.J. Plauger wrote a “recipe” on how to get started in any new programming lan‐
guage 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 runna‐
ble program as needed, and run it. And once you’d done that you could, with elabora‐
tion, 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
programming 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.
1
30. 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 displays data into that screen and 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 for 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.
• Sync adapters synchronize data with cloud services; the best-known examples are
the Contacts and Calendar apps 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 the invocation of Activities, Services, etc., using an Intent, an object that
specifies your intention to have something done. Intents can start Activities within
your application (by class name), start Activities in other applications (by specifying
content type and other information), start Services, and request other operations. The
interactions among these components are outlined in Figure 1-1.
Of these, the Activity is the most basic component, and the place you need to start
when learning to develop Android applications.
Reference Documentation
Every Android developer should probably save at least these bookmarks or favorites
in their browser for quick reference at any time:
• Introductory Documentation
• Android API Reference
2 | Chapter 1: Getting Started
31. 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 methods
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.
Figure 1-1. Android application components
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.
1.2 Understanding the Android Activity Life Cycle | 3
32. • 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
The system’s call to onCreate() is how you know that the Activity has been started. This
is where you normally do constructor-like work such as setting up the “main win‐
4 | Chapter 1: Getting Started
33. dow” 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 Activity needs.
Note that most applications today base their UI on Fragments. A Fragment is a part 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 Activity can be
divided into multiple Fragments (see Recipe 6.7), which solves this problem. A Frag‐
ment can only exist inside an Activity. The Fragment life cycle is similar to that of the
Activity, 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 life-cycle methods with log “debug” state‐
ments (see also Recipe 3.11):
@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, KitKats,
Marshmallows, and Nougats, 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, 2.3.3, 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 APIs; when the second digit
changes, it’s more evolution than revolution (and occasionally a new code name); and
if only the third digit changes, it’s a minor change. The API levels are numbered
monotonically. 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 (unless
special care is taken; see Recipe 1.21). An app built for 1.5 should run without recom‐
pilation on Android 7, for example. But an app written for and compiled on Android
1.3 Learning About Android Releases | 5
34. 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
tricks that we’ll touch on later (Recipe 1.21). The major versions of Android are sum‐
marized in Table 1-1.
Table 1-1. Android versions
Version number API level Name Datea Major change/Notes CM version
1.0 1 2008-09-23
1.1 2 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 14.0
7.1 25 Nougat 14.1
a Date information sourced from Wikipedia.
The final column, “CM version,” shows the main version numbers of CyanogenMod,
long the leading “alternate distribution” or “community build” of Android. Based on
the Android Open Source Project, “CM” was much beloved by many open source
fans because it was independent of Google, allowed easier “root” access, and so on. As
this edition of this book was going to press, CyanogenMod, Inc. decided to terminate
its support for CyanogenMod, leading the community to fork the project and rename
it to LineageOS. There are many other community builds of Android. One focusing
on security is CopperheadOS. Several others are built by people frequenting XDA
6 | Chapter 1: Getting Started
35. Developers groups. Several commercial outfits claim to offer community builds, too;
a web search will find these.
Of course, this table will continue to grow as new versions are released, and Android
continues to grow.
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 the 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). This is a good introduction for
programmers, particularly those who are coming from C/C++. The book has
grown from an acorn to a coconut in size through its various editions, 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).
1.4 Learning the Java Language | 7
36. • “Great Java: Level 1,” by Brett McLaughlin (O’Reilly). This video provides a visual
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‐
sions, numbers, dates and times, structuring data, I/O and directories, interna‐
tionalization, threading, and networking, all of which apply to Android. It also
has a number of chapters that are specific to Swing and to some EE-based tech‐
nologies.
• Java Testing for Developers, a video series I did on how to test out Java code as
you develop it; covers both dynamic testing (with JUnit and many others) and
static testing (with tools such as PMD and FindBugs).
Please understand that this list will probably never be completely up-to-date.
See Also
I maintain a list of Java resources online at http://www.darwinsys.com/java/.
O’Reilly has many of the best Java books around; there’s a complete list at http://
oreilly.com/pub/topic/java.
1.5 Creating a “Hello, World” Application from the
Command Line
Ian Darwin
Problem
You want to create a new Android project without using any IDEs or plug-ins.
Solution
Use the Android Software Development Kit (SDK) tool android with the create project
argument and some additional arguments to configure your project.
Discussion
This discussion assumes you have installed the Android SDK—one of the easiest
ways to do so is to follow Recipe 1.8—and installed at least one platform version.
In addition to being the name of the platform, android is also the name of a command-
line tool for creating, updating, and managing projects. To use it, you can either navi‐
8 | Chapter 1: Getting Started
37. gate into the android-sdk-nnn directory or set your PATH variable to include its tools
subdirectory.
You have a choice of creating your project in the old format, which is the default, or
the “new” Gradle-based format. We’ll show the old way first, then the Gradle way. To
create a new project, give the command android create project with some arguments.
Example 1-1 shows running the command in a terminal window in a Microsoft envi‐
ronment.
Example 1-1. Creating a new project—old format
C:> PATH=%PATH%;"C:Documents and SettingsIanMy Documentsandroid-sdk-windowstools";
C:Documents and SettingsIanMy Documentsandroid-sdk-windowsplatform-tools"
C:> android create project --target android-21 --package com.example.foo
--name Foo --activity HelloWorldActivity --path .MyAndroid
Created project directory: C:Documents and SettingsIanMy DocumentsMyAndroid
Created directory C:Documents and SettingsIanMy DocumentsMyAndroidsrccomexamplefoo
Added file C:Documents and SettingsIanMy
DocumentsMyAndroidsrccomexamplefooHelloWorldActivity.java
Created directory C:Documents and SettingsIanMy DocumentsMyAndroidres
Created directory C:Documents and SettingsIanMy DocumentsMyAndroidbin
Created directory C:Documents and SettingsIanMy DocumentsMyAndroidlibs
Created directory C:Documents and SettingsIanMy DocumentsMyAndroidresvalues
Added file C:Documents and SettingsIanMy DocumentsMyAndroidresvaluesstrings.xml
Created directory C:Documents and SettingsIanMy DocumentsMyAndroidreslayout
Added file C:Documents and SettingsIanMy DocumentsMyAndroidreslayoutmain.xml
Added file C:Documents and SettingsIanMy DocumentsMyAndroidAndroidManifest.xml
Added file C:Documents and SettingsIanMy DocumentsMyAndroidbuild.xml
C:>
On Unix or macOS you can use something like the following:
/Users/ian/android-sdk-macosx/tools/android create project --target android-21
--package com.example.foo
--name Foo --activity HelloWorldActivity --path MyAndroid
Table 1-3 lists the arguments for the android create project command.
Table 1-3. List of android create project arguments
Name Meaning Example
--activity Name of your “main class” and default name for the generated .apk file. --activity
HelloWorldActivity
--name Name of the project and the generated .apk file. --name MyProject
--package Name of the Java package for your classes. --package
com.example.hello
--path Path to create the project in (does not create a subdirectory under this, so
don’t use /home/you/workspace, but
rather / home / you / workspace / NewProjectName).
--path /home/ian/
workspace/MyProject
(see Example 1-1 for
Windows example)
1.5 Creating a “Hello, World” Application from the Command Line | 9
38. Name Meaning Example
--target API level of the Android platform to target; use android list targets
to see list of targets. A number is an “ID,” not an API level; for that, use
android- with the API level you want.
--target android-10
--gradle Use Gradle format (requires --gradle-version). --gradle
--gradle-
version
Version of Gradle plug-in to use. --gradle-version 3.3
If it cannot complete the requested operation, the android command presents a volu‐
minous “command usage” message listing all the operations it can do and the argu‐
ments for them. If successful, the android create project command creates the files and
directories listed in Table 1-4.
Table 1-4. Artifacts created by android create project
Name Content
AndroidManifest.xml Config file that tells Android about your project
bin Generated binaries (compiled class files)
build.properties Editable properties file
build.xml Ant build control file
default.properties or project.properties (depending on tools
version)
Stores SDK version and libraries used; maintained by plug-in
gen Generated stuff
libs Libraries, of course
res Important resource files (strings.xml, layouts, etc.)
src Source code for your application
src/packagename/ActivityName.java Source of “main” starting Activity
test Copies of most of the above
If we use the two Gradle-related arguments, we get a slightly different project struc‐
ture, as shown in Example 1-2.
Example 1-2. Project creation—Gradle format
$ /Users/ian/android-sdk-macosx/tools/android create project
--target android-23 --package com.example.foo
--gradle --gradle-version 2.0.0
--name Foo --activity HelloWorldActivity --path HelloGradle
Created project directory: HelloGradle
Created directory /home/ian/HelloGradle/src/main/java
Created directory /home/ian/HelloGradle/src/main/java/com/example/foo
Added file HelloGradle/src/main/java/com/example/foo/HelloWorldActivity.java
Created directory /home/ian/HelloGradle/src/androidTest/java
Created directory /home/ian/HelloGradle/src/androidTest/java/com/example/foo
Added file...
10 | Chapter 1: Getting Started
39. HelloGradle/src/androidTest/java/com/example/foo/HelloWorldActivityTest.java
Created directory /home/ian/HelloGradle/src/main/res
Created directory /home/ian/HelloGradle/src/main/res/values
Added file HelloGradle/src/main/res/values/strings.xml
Created directory /home/ian/HelloGradle/src/main/res/layout
Added file HelloGradle/src/main/res/layout/main.xml
Created directory /home/ian/HelloGradle/src/main/res/drawable-xhdpi
Created directory /home/ian/HelloGradle/src/main/res/drawable-hdpi
Created directory /home/ian/HelloGradle/src/main/res/drawable-mdpi
Created directory /home/ian/HelloGradle/src/main/res/drawable-ldpi
Added file HelloGradle/src/main/AndroidManifest.xml
Added file HelloGradle/build.gradle
Created directory /home/ian/HelloGradle/gradle/wrapper
$
It is a normal and recommended Android practice to create your user interface in
XML using the layout file created under res/layout, but it is certainly possible to write
all the code in Java. To keep this example self-contained, we’ll do it the “wrong” way
for now. Use your favorite text editor to replace the contents of the file Hello‐
World.java with the contents of Example 1-3.
Example 1-3. HelloWorld.java
import android.app.Activity;
import android.widget.*;
public class HelloWorld extends Activity {
/**
* This method gets invoked when the Activity is instantiated in
* response to, e.g., clicking on the app's icon in the Home screen.
* Reminder: this is NOT a best-practices way of creating the UI!
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a TextView for the current Activity
TextView view = new TextView(this);
// Make it say something
view.setText("Hello World");
// Put this newly created view into the Activity,
// sort of like JFrame.getContentPane().add(view)
setContentView(view);
}
}
Although Google has moved from Eclipse to Android Studio, which uses the Gradle
build tool, the command-line version of generated projects still uses the Ant build
tool by default (i.e., if you omit the two Gradle-related arguments shown in
Example 1-2). Assuming you have the Apache Software Foundation Ant build tool
installed (and it is included with recent versions of the Android SDK), you can now
1.5 Creating a “Hello, World” Application from the Command Line | 11
40. (in a command-line window) change to the project directory (…MyDocumentsMyAndroid
in Example 1-1) and issue the command:
$ ant debug
This will create an archive file named, for example, MyAndroid.apk (with “apk” stand‐
ing for Android Package) in the bin directory.
If you are using the Gradle version, you can instead type:
gradlew build
The first time you run this, it may take a long time to complete. But it should work. If
it doesn’t, use the HelloGradle project in this book’s GitHub repository.
If this is your first time here, you may need to create an Android Virtual Device
(AVD), which is just a named configuration for the Android emulator specifying tar‐
get resolution, API level, and so on. You can create an emulator using:
android create avd -n my_droid -t 21
The argument to -t is the target API level; see Recipe 1.3. For more details on creating
an AVD, see Recipe 3.1.
You can then start the Android Debug Bridge (ADB) server for communication, and
the emulator:
adb start-server
emulator -avd my_droid -t 19
Assuming you now have either the emulator running or your device plugged in and
recognized via USB, you can issue a command similar to one of the following,
depending on exactly what you built earlier. If you have both an emulator and a real
device, add an argument of -e for emulator or -d for device between the adb command
and the install operation:
$ adb install -r bin/HelloAndroid.apk # Ant build
$ adb install -r target/HelloAndroid-1.0-SNAPSHOT-debug.apk # Maven build
$ adb install -r build/outputs/apk/HelloAndroid-debug.apk # Gradle build
If you are handy with shell scripts or batch files, you’ll want to create one called, say,
download, to avoid having to type the adb invocation on every build cycle.
Finally, you can start your app! You can use the application list: tap the little icon that
looks like a 5×5 row of dots, scroll to your application by name, and tap its icon.
You will probably find it convenient to create an icon for your app on the Home
screen of the device or emulator; this icon will survive multiple install -r cycles, as
long as you don’t uninstall, so it’s the easiest way to test the running of your applica‐
tion.
12 | Chapter 1: Getting Started
41. See Also
Recipe 1.10, Recipe 1.15.
1.6 Creating a “Hello, World” App with Apache Maven
Ian Darwin
Problem
The previous recipe used Android to create a project buildable with Apache Ant.
However, many organizations are moving or have moved from Ant to Maven, due to
Maven’s dependency management. In fact, Maven is almost certainly the most widely
used build tool in the Java environment. Ant doesn’t handle dependencies on its own;
although this can be grafted in (using Apache Ivy), Maven’s shorter configuration files
make direct use of Maven a better fit most of the time.
Solution
Use Apache Maven. Use a “Maven archetype” to generate your project, and use
Maven to build and run it.
Discussion
There are several approaches to using Apache Maven to build Android projects.
Here’s one I’ve tested, based upon the akquinet maven-android-archetypes:
$ mvn archetype:generate
-DarchetypeArtifactId=android-quickstart
-DarchetypeGroupId=de.akquinet.android.archetypes
-DarchetypeVersion=1.0.8
-DgroupId=com.androidcookbook
-DartifactId=android-demo
-Dplatform=17
-Dpackage=com.androidcookbook.hellomaven
Most of the -D arguments are obvious. platform is the API level. You can specify a
number of other parameters and variations, including test projects.
Once you’ve created your project you can build it:
$ mvn clean package
1.6 Creating a “Hello, World” App with Apache Maven | 13
42. Before the next step, you should plug in a device or start an emulator:
$ mvn android:deploy
# (not mvn deploy!) this will package and install, but not run, the app
$ mvn android:run # This will run the app
Maven and its Android plug-in offer support for other operations, including signing
the APK for release.
There are also Eclipse plug-ins for Maven; these are included with the latest Eclipse
builds, or see Recipe 1.16 and use the Marketplace to install M2E and M2E-Android.
It is possible to “Eclipsify” a project such as the one you created using Maven. You
can create minimal Eclipse project structures using mvn eclipse:eclipse, and make it
into a full M2E project by right-clicking on the project in the Project Explorer and
selecting Configure → Convert to Maven Project. This has been done to create many
of the Eclipse files in the downloadable version of this project.
Incidentally, if you get an Eclipse error on your POM file stating “Plugin execution
not covered by lifecycle configuration,” you can turn this into a warning or even
ignore it, under Eclipse Preferences → Maven → Errors/Warnings → Plugin execu‐
tion not covered by lifecycle configuration → Warning, as shown in Figure 1-3.
Figure 1-3. Maven: Plugin execution not covered by lifecycle configuration
14 | Chapter 1: Getting Started
43. See Also
Akquinet’s guide to getting started with archetypes; the source code for the artifacts.
I have an experimental Maven archetype that creates a Maven project that should also
work with Eclipse and Android Studio; you can try it out by referring to GitHub.
1.7 Choosing an IDE for Android Development
Ian Darwin
Problem
Using build tools is OK, but coding with a plain-text editor is too slow to be your
regular development stream. You want to choose an integrated development environ‐
ment (IDE) to use for your Android projects: Android Studio, Eclipse, or “other.”
Solution
Weigh the pros and cons of each, then roll the dice. Try each one on a reasonable-
sized project.
Discussion
Whereas in the MS Windows world there is a single IDE that dominates, and in the
Android world there is a single IDE that is “official,” in the larger Java world there are
several that are worth considering.
Eclipse was created by IBM in the early days of Java, once it was clear that its then-
current IDE Visual Age was not going to live a long life (Visual Age was written in
Smalltalk, not in Java). In my experience teaching Java courses, about 80% of Java
developers use Eclipse, and that figure has been fairly steady over the years. Spring
Tool Suite (STS) and various IBM developer studios are based on Eclipse and
included in that figure.
Android Studio is the official Android IDE supported by Google. It is based on Intel‐
liJ IDEA, a Java IDE that has long been around but had a relatively small usage level
in the Java community until Google incorporated its plug-in into ItelliJ and renamed
this version to “Android Studio.”
NetBeans was written by a small company that Sun Microsystems acquired in 1999.
Sun Microsystems was in turn acquired by Oracle in 2009. NetBeans has been the
“official” Java IDE for a long time, but its usage was “eclipsed” by Eclipse (remember:
an eclipse occurs when another body passes in front of the Sun). Relatively few devel‐
opers use NetBeans specifically for Android, so to keep the discussion focused, Net‐
Beans will not be covered in this book.
1.7 Choosing an IDE for Android Development | 15
44. For the first decade of Android’s life, Google recommended use of Eclipse with its
own plug-in, called Android Development Tools (ADT). Google offered it both as a
standalone plug-in (for those who already had Eclipse up and running) and in a bun‐
dle already integrated with Eclipse. Around 2013 it announced the switch to Android
Studio based on IntelliJ. Shortly thereafter, the Eclipse Foundation announced that a
small team was picking up ADT (since it was open source) and merging in some
additional tools. This new plug-in is called AndMore. Eclipse with AndMore is equiv‐
alent to and forward-compatible with Eclipse with ADT, though some names in the
project files have to be changed (see Recipe 1.11). Note that some organizations may
choose to stay with ADT; if you’re in that camp, you can (mostly) just substitute ADT
where we say AndMore.
Your project structure and accompanying build tool might also be a factor in choos‐
ing. Eclipse supports a single-level project, which is typically what you need for an
application, with an optional second project for testing if you use the official Android
unit testing framework (see Chapter 3). ADT (and thus AndMore) does not require
an external build tool; the plug-in contains all the smarts to build any type of Android
application. It has only two project files that need to be kept under source con‐
trol: .project and .classpath. A directory .settings file can be controlled as well, but it
changes a lot and can just as easily be ignored. There is even an API in Eclipse for
manipulating project structure. Because there are only two files, hacking a project by
editing configuration files is not out of the question. As well, Eclipse is well supported
by the Maven build tool using the M2E (Maven Eclipse) and M2E-Android plug-ins
(you’ll want both). However, this setup can be a little bit quirky.
Android Studio, on the other hand, uses a maze of project files. Here is a list of the
files (not including the source of your program!) in a project created by Android Stu‐
dio 2.0:
./.gradle/2.4/taskArtifacts/cache.properties
./.gradle/2.4/taskArtifacts/cache.properties.lock
./.gradle/2.4/taskArtifacts/fileHashes.bin
./.gradle/2.4/taskArtifacts/fileSnapshots.bin
./.gradle/2.4/taskArtifacts/outputFileStates.bin
./.gradle/2.4/taskArtifacts/taskArtifacts.bin
./.idea/.name
./.idea/compiler.xml
./.idea/copyright/profiles_settings.xml
./.idea/encodings.xml
./.idea/gradle.xml
./.idea/libraries/appcompat_v7_23_0_1.xml
./.idea/libraries/design_23_0_1.xml
./.idea/libraries/hamcrest_core_1_3.xml
./.idea/libraries/junit_4_12.xml
./.idea/libraries/support_annotations_23_0_1.xml
./.idea/libraries/support_v4_23_0_1.xml
./.idea/misc.xml
./.idea/modules.xml
./.idea/runConfigurations.xml
16 | Chapter 1: Getting Started
45. ./.idea/workspace.xml
./build/ - ignore
./build.gradle
./gradle/wrapper/gradle-wrapper.jar
./gradle/wrapper/gradle-wrapper.properties
./gradle.properties
./gradlew
./gradlew.bat
./local.properties
./MyApplication.iml
./settings.gradle
./mainapp/.gitignore
./mainapp/build.gradle
./mainapp/mainapp.iml
./mainapp/proguard-rules.pro
It appears to take Android Studio about 30 files to do what Eclipse does in just a few.
Admittedly not all of those have to be kept under source control, but which ones do?
To answer that, look in the .gitignore file in a project generated by Android Studio 2.x;
this lists the files that should not be included in source control.
Android Studio also expects that every project have an extra level of directory struc‐
ture, called app for the application, to cater to the relatively few applications that have
multiple modules, such as a library. In Eclipse, you just make the project using the
library depend on the library project. The extra directory structure put in by Studio
encumbers pathnames, means the directory where a Studio project is created does
not conform to the decade-old Maven project structure, and means that you can’t use
the old familiar grep -r somePattern projectname/src; you have to remember to type an
extra “app/” every time. Seemingly harmless, but annoying. Of course people who
commonly use multiple projects but forget to create them as such when they start will
appreciate the way Studio does things.
You should also consider speed. Both are fairly quick at entering code you type.
Because Studio is not a complete IDE but depends on Gradle to build, it used to be a
lot slower, but Studio 2.x is supposed to be much improved in this regard. Different
people have different ideas on how to measure speed, and different results have been
claimed, so you should try this yourself on representative development hardware.
Eclipse provides a single window with a tree-based “Package Explorer,” so you can
easily move, copy, or compare files between projects. IntelliJ/Studio opens each
project in a new window and, by default, closes the previous one.
So, there are many differences, but also many obvious similarities. It’s sort of like buy‐
ing a car: GM, Ford, Chrysler, Tesla, BMW, Toyota, and many more make automo‐
biles, but you have to pick one of these to buy. With IDEs the choice is not as exclu‐
sive, though. What if you like both? You could use Eclipse for your regular Java work
and IntelliJ/Android Studio for your Android work—especially if you need the latest
Android support—although switching back and forth might be annoying. You could
1.7 Choosing an IDE for Android Development | 17
46. even set up your Android projects to be openable in both IDEs—we’ve done so for
most of the projects in the samples repository. However, it’s not a very profitable
undertaking, and we don’t recommend it as a general practice.
Oh, and if you do run both, be sure to configure them to share the same “SDK” folder
—the actual Android tools, libraries, and emulator images—so you won’t have to
update everything twice.
As another path forward for the experienced Eclipse user, you could use Android
Studio but tell it to use the Eclipse key-mappings, which will make it work somewhat
like Eclipse—although many of the key sequence settings there are not quite right,
and you’ll need to fiddle with them a bit. And if you do so but another developer in
your team is a “native” user of Studio or the underlying IntelliJ, you will both get frus‐
trated when doing pair programming.
Summary
If you want the best support of new features, Android Studio may be a better choice.
If you want an IDE that is widely used across the Java community, Eclipse may be a
better choice. There is no hard and fast answer.
1.8 Setting Up Android Studio
Daniel Fowler, Ian Darwin
Problem
You want to develop your Android applications using Android Studio, so a concise
guide to setting up that IDE would be useful.
Solution
The use of the Android Studio IDE is recommended by Google for developing
Android apps. Configuring the IDE is not a single-shot install; several stages need to
be completed. This recipe provides details on those stages.
Discussion
The Android Studio integrated development environment (IDE) is provided for free
by Google to develop applications. Studio comes with the Android Software Develop‐
ment Kit (SDK), which provides essential programs to develop Android software. To
set up a development system you will need to download and run the installers for:
• The Java Standard Edition Development Kit (JDK), if not already installed
18 | Chapter 1: Getting Started
47. • Android Studio
Installing the JDK, if necessary
Go to the Java download page. Click the Java icon to access the JDK downloads:
The list of JDK downloads will be shown. Click the Accept License Agreement radio
button; otherwise, you will not be allowed to continue. You’ll want to download and
run one of the latest JDKs present; as of this writing, they are Java 8 builds whose ver‐
sion string ends in 8u121, but that will surely change by the time you read this.
Choose the download appropriate for your operating system: Windows x86 or 64-
bit.exe, MacOS .dmg, Linux .rpm or .tgz, and so on. Accept any security warnings that
appear, but only if you are downloading from the official Java download web page.
When the download has completed, run the installer and go through all the screens,
clicking Next until the installer has finished. You should not need to change any
options presented. When the JDK installer has completed, click the Finish button. A
product registration web page may load; you can close this or you can choose to reg‐
ister your installation.
For Android use, you do not need to download any of the “demos or samples” from
this site.
Install Android Studio
Go to the Android Studio download page.
The installation process can take some time as the installer will download additional
files. Click the Download Android Studio button, accept the terms and conditions,
and begin the download by clicking a second Download Android Studio button. On
MS Windows, the default is a file with a name like android-studio-bundle-X.X-
windows.exe, which is over 1 GB and includes both the IDE and the Android SDK. If
you already have the Android SDK installed, select Other Download Options and you
will see the page in Figure 1-4, where you have a choice of that file or one without the
SDK bundle, with a name like android-studio-ide-X.X-windows.exe. For macOS there
is only the unbundled file, android-studio-ide-X.X-mac.dmg, where X.X is Studio’s
build number (this may not match the displayed version number; e.g., Android
1.8 Setting Up Android Studio | 19
48. Studio 2.0 has a build number of 143.2739321). On Windows, accept the Windows
User Account Control dialog.
On some 64-bit versions of Windows the installer may require the JAVA_HOME environ‐
ment variable to be set. Use the Control Panel to access the System settings, and open
the “Advanced systems settings” section. The Advanced tab on the System Properties
dialog should be visible. Click the Environment Variables button to add a new
JAVA_HOME system variable, and set it to the path of the Java JDK (e.g., C:Program Files
Javajdk1.8.0; enter the correct path for your system).
Figure 1-4. Android Studio download page
Proceed through the installer’s dialogs. The installer configures Studio and the
Android SDK (if you installed the bundle version), and downloads an initial Android
Virtual Device (AVD). The default install location for the Android SDK is under the
logged-in user’s AppDataLocal directory on Windows, or $HOME/android-sdk-nnn
under macOS or Linux. You may want to select an easier-to-remember and shallower
location (e.g., C:AndroidSDK).
After installing Studio, further configuration (and downloading of the SDK if neces‐
sary) occurs when it is first run. Allow access through your desktop system’s configu‐
ration if required. Further SDK packages will be downloaded. As well, each time Stu‐
dio runs it checks for updates and may display a message if updates are needed. Aside
from updates to Studio itself, the Android SDK and additional SDK packages are best
updated via the Android SDK Manager program (see Recipe 1.9).
Once that’s done, Studio is now configured to build and debug Android apps. See
Recipe 3.1 to configure an Android emulator; then try a “Hello, World” app as a
20 | Chapter 1: Getting Started
49. sanity check. Or plug a real Android device into the computer’s USB port and use its
settings to turn on USB Debugging.
For a few Windows users Studio may not start the first time, and a
DLL error is displayed. Installing the Microsoft Visual C++ 2010
SP1 Redistributable Package has been known to clear the error.
See Also
Recipe 3.1, Recipe 1.9.
1.9 Installing Platform Editions and Keeping the SDK
Updated
Daniel Fowler
Problem
Whether using Android Studio, Eclipse, or command-line tools, you must install at
least one Platform Edition before you can compile applications. The SDK should be
kept updated so you can work with the latest APIs on the evolving Android platform.
Solution
Use the Android SDK Manager program to install, and later to update, the installed
SDK packages and to install new SDK packages.
Discussion
Android itself is constantly evolving, and therefore so is the Android Software Devel‐
opment Kit. The ongoing development of Android is driven by:
• Google’s research and development
• Phone manufacturers developing new and improved handsets
• Addressing security issues and possible exploits
• The need to support new devices
• Support for new hardware interfaces
• Fixing bugs
• Improvements in functionality (e.g., a new JavaScript engine)
• Changes in the underlying Linux kernel
1.9 Installing Platform Editions and Keeping the SDK Updated | 21
50. • Deprecation of redundant programming interfaces
• New uses (e.g., Android Wear, Android Auto)
• The wider Android development community
The following discussion is illustrated with screenshots from
Android Studio, but the same tooling can be invoked from within
Eclipse or by invoking the command-line tool named simply
android.
Installation of the IDEs and the Android SDK has been covered elsewhere; see Recipe
1.8 or the developer documentation. When Android Studio is run it will check for
updates to both Studio and the SDK. A message is displayed when updates are avail‐
able. Most updates will be performed via the SDK Manager program. If you OK the
update, Studio will close and the SDK Manager will run. If you don’t want to update
when the upgrade is offered, you can access the SDK Manager later from within Stu‐
dio (see Figure 1-5) or directly from the Android SDK install location.
Figure 1-5. SDK Manager toolbar icon
The following steps work through the update process.
In Studio, selecting SDK Manager from the toolbar or via the Tools → Android menu
shows the Android SDK settings, which shows what packages are installed or avail‐
able (see Figure 1-6).
22 | Chapter 1: Getting Started
51. Figure 1-6. Android SDK settings, showing current installation status
To actually make changes, click the Launch Standalone SDK Manager link, which
runs the external SDK Manager program shown in Figure 1-7. The Android SDK is
divided into several packages. The SDK Manager automatically scans for updates to
existing packages and will list new packages. Available updates will be shown in a list
(alongside available optional packages).
Figure 1-7. Standalone SDK Manager
Available updates will be checked ready for download and installation; uncheck the
ones not required. (Unless you’re short on disk space, you can have as many of the
1.9 Installing Platform Editions and Keeping the SDK Updated | 23
52. API packages installed as you wish.) Then click the “Install x packages” button. If an
update or package has license terms that require accepting, they will be listed. High‐
light each package to read the license terms, and then accept or reject the package
using the radio buttons. (Rejected packages will be marked with a red cross.) Alterna‐
tively, highlight the parent package and click Accept All to accept everything that is
available. All packages and updates ready to download and install will be shown with
a green tick. Click Install; while the download and installation is progressing, you can
view the log by clicking the log icon in the bottom right of the Android SDK Manager
dialog (see Figure 1-8).
Figure 1-8. Android SDK update log
Any errors during the download and installation will be shown in red in the log dia‐
log. Updates that affect the Android Debug Bridge (ADB) will result in a request to
restart ADB; click Yes to restart it. Obsolete packages will have been deleted during
the download and installation. When all packages have been updated and you’ve had
a chance to inspect the log, you can close the log dialog, if open, and the Android
SDK Manager dialog.
Android is an evolving platform, so checking for updates every few weeks allows you
to work with the latest tools and APIs.
See Also
Recipe 1.8, The Android Studio User Guide documentation on installation.
24 | Chapter 1: Getting Started
53. 1.10 Creating a “Hello, World” App Using Android Studio
Ian Darwin
Problem
You want to use Android Studio to develop your Android application.
Solution
Install Java, Android Studio, and one or more SDK versions. Create your project and
start writing your app. Build it and test it under the emulator, all from within the IDE.
Discussion
Before you can create your application with Android Studio, you have to install these
two packages:
• Android Studio itself
• One or more Android SDK versions
For details on installing these items, please refer to Recipe 1.8.
Once you’ve done that, click on “Start a new Android Studio project” from the Wel‐
come screen (Figure 1-9), which appears when you don’t have any projects open.
Figure 1-9. Studio Welcome screen
1.10 Creating a “Hello, World” App Using Android Studio | 25
54. On the Create New Project screen (Figure 1-10), choose the application name and
Java code package.
Figure 1-10. Studio New Project screen
On the next page of the same dialog, you can specify what kinds of devices (phone/
tablet, Android Wear, Android TV, etc.) your project is going to target and, for
mobile devices, the minimum and target SDK API levels (Figure 1-11).
Almost every Android application has at least one Activity class defined, and the
“Hello, World” app is no exception. You can either pick Empty Activity (in which case
you’ll have to add some code) or Basic Activity; we went with the latter (Figure 1-12).
The next page asks you to pick names for your Activity and its layout file
(Figure 1-13). For a single-Activity app, the defaults are fine.
26 | Chapter 1: Getting Started
56. But it had to be admitted that this sounded more ridiculous than
impressive. And not one of the courtiers, officers, or magistrates felt
individually powerful enough to set himself by voice and bearing
against that forceful speaker. Each felt that he would appear
theatrical. And the man in the grey cloak, up above there, was not
that. Besides, the assembly gave no countenance to such effort, and
was, like every great gathering of people, under the influence of the
most powerful personality.
At last, the organist comprehended what was desired of him in this
critical situation, and drawing out all the stops he sent forth a heavy
peal of trembling sound. In the meantime, two policemen were
despatched aloft to silence the undesirable speaker.
But the majestic music rang out upon the words of Markus as if in
solemn confirmation. So at least it seemed to Johannes, and to
many others in the church. Markus ceased speaking, and appeared
to be listening, pensively.
The policemen returned without having attained their object. The
gallery could only be reached by climbing over a great beam, having
broken and decayed supports, one hundred feet above the floor. The
officers, becoming dizzy, lost their zest for the affair, and the firemen
had to be sent for.
The music stopped again, and yet there was no continuance of the
ceremonies. Markus still stood calmly in his elevated place, looking
down upon the throng below with that sad expression of
countenance which Johannes knew so well. And yet again, softer,
but with keen and cutting penetration:
"Oh, ye poor, poor people! Slaves of the devil, called custom!
"You know no better, and cannot do otherwise. You mean to perform
your duty, and to reach that which is good and holy.
"How would you possibly find your King? And how would you
maintain order—holy order—without these two people; without him
57. whom you happen to have named your king, as you might have
named some foundling?
"But notwithstanding you have felt, every one of you, that I spoke
the truth just now, you yet will continue this unblushing lie because
you dare not do otherwise, and because you know no other way.
"But bethink yourselves, unhappy beings! Cowardice and weakness
shall not excuse you, if, knowing the lie, you adhere to it, and,
seeing the truth, you accept it not.
"What you endure is indeed terrible. I esteem you still more worthy
of pity than the neglected people out of whose misery you have
extracted your splendor.
"You have burdened this poor pair of human beings with royalty—a
power befitting only the strongest and the wisest among men.
"Thus do you crush their weak spirits under a weight which only the
strongest can bear. You desecrate the name of King—you blaspheme
against God, whose grace is not subject to your command.
"You dazzle your bewildered people with a blinding glare, as if they
truly had a king. But it is an idle puppet-show, to comply with a
hollow peace and a defective method. There is none among you who
has the wisdom and the might to lead this people into
righteousness; and yet you bear all the responsibility for their
confusion, their ignorance, their crudeness, and their misery.
"And they are the least guilty, because, in working for your luxury,
they miss the opportunity to learn.
"But you pride yourselves upon your knowledge and your
refinement. You know how the industrious lack food, and the rich
have the privilege of idleness. You know how an over-abundance
flows to you from the deprivations of the neglected. You know the
injustice of all this, and yet permit it. And on these two unfortunates
you impose the responsibility and the lie.
58. "But you know—and you shall not be justified!
"And you, two unfortunates, corrupted by the burden of your
imposed greatness—poor man, poor, poor little woman! The
superhuman power to break the spell of lies round about you will not
be yours. May the Good Father, who hath not poured out His grace
upon you, encompass you with His compassion."
Just then an excited young adjutant drew out a revolver, and cried,
"He insults the Queen!"
A more moderate diplomat, fearing a panic, held back his hand. The
cry "He insults the Queen!" was repeated at the entrance to the
church. And an uproar was heard outside, for, at the coming of the
firemen, the waiting crowds had overheard something about a
murderer, or a madman, who was in the upper part of the church.
The helmeted men now appeared in the small gallery, and dragged
Markus aside. They immediately bound him with strong cords,
fearing he might throw them down below. Then one of them first
made his way over the big beam, and ordered Markus to come to
him. After that, the other cautiously followed.
The assembly could not see this, because it took place in the dark
ridge of the aisle; but all breathed freely once more, now that the
powerful voice up above was silent. Again the organ pealed forth,
and the royal pair, ceremoniously preceded by the court official, at
last proceeded toward the exit, for the carriages were now ready.
The singing by the children was omitted. Everything else went just
as the daily papers have recorded it for you.
59. Markus, tightly bound, was led out through a side door, yet not so
secretly but that the crowd became aware thereof, and a riotous
mob soon encircled the firemen and their prisoner.
"The Queen insulted!" they shrieked. "Kill him! Orange forever!" And
they pressed closer and closer.
When Johannes and Marjon, hurried and breathless, had forced their
way out through the disorderly throng, they saw, in the distance,
above the encircling crowds, the shining helmets, swaying and
undulating as they gradually moved farther and farther away. Hands,
hats, walking-sticks, and umbrellas could be seen, now uplifted and
then lowered.
The two followed on, in extreme anxiety, but they were not so
fortunate as to get close by. They saw the red, angry faces of men
and women, and heard the shouts of, "Orange forever!" and "Kill
him!" At last, to their relief, they saw approaching a long file of
policemen, who forced their way through the crowd. The people now
pressed closely about the entrance to a narrow alley in which was
the police-station. Then Johannes saw a man take up a large iron
ash-can that stood on a stoop at the corner of the alley, and toss it
so that it came down in the middle of the clamoring crowd where
Markus was. A great cloud of yellow-white ashes flew from it, and
the rabble laughed and cheered. The police cleared the alley, and
the mob slowly scattered, with the triumphant shout: "Orange
forever!"
When Johannes peered into the alley, between the policemen who
would not let him through, he saw Markus—no longer walking, but
only an inert body under the weight of which the firemen were
moving with shuffling feet.
Marjon and Johannes waited patiently during what seemed an hour.
It might have been only fifteen minutes. Then they obtained
permission to pass through, and to see their brother in the station-
house.
60. When questioned, an officer, who was sitting at the entrance,
pointed over his shoulder with his pipe-stem to a dark corner.
There, upon the wooden floor, unconscious, lay Markus. His clothing
was torn to rags; his hair, his beard, his eyebrows and lashes, were
white with ashes; and over all were dark red clots and streaks of
coagulated blood. He breathed heavily and painfully. There was no
one close beside him, and he lay unwashed and uncared for, with
the rope still around his wrists.
Johannes and Marjon asked for water, but were not permitted to do
anything. They had to wait until the municipal doctor came. Tightly
clasping each other's hand, they waited, watching their friend. At
last the doctor came, and cut away the rope. It was not a mortal
hurt, he said.
They saw the ambulance, with its white awning come, and saw
Markus laid therein. Then, hand in hand, they walked behind to the
door of the hospital, without speaking a word.
That evening there were great rejoicings and brilliant illuminations in
all the towns and villages of the dear Netherlands. Everywhere there
were flaming torches and exploding fireworks, and on all sides rang
strains of "Wilhelmus!" and "Orange forever!"
The King and Queen were glad when at last the day was ended.
XXII
Johannes and Marjon both held out bravely until night, doing their
daily work as well as they could, and telling briefly, to the few
faithful friends of Markus, what had occurred.
61. But when the lonesome night was come, and they were about to
part for several hours, Johannes said:
"No, do not go away from me! How can I endure it—alone with my
thoughts—without you!"
They were in the little kitchen where Marjon slept. A small lamp,
without a shade, stood burning on the table beside an untidy coffee-
set.
When Johannes said this, Marjon looked at him with puzzled, half-
closed eyes, as if she did not understand and was trying to think it
out. Then she threw herself forward upon her pillow, her face in her
hands, and began to cry piteously.
At that Johannes also broke down, and kneeling beside her poor,
rickety little iron bed, he cried with her like one in desperation.
Then said Johannes: "What shall we do without him, Marjon?"
Marjon made no reply.
"Do you remember that he said he should soon go away from us?"
"If only I could nurse him," she said.
"Is he going to die?" asked Johannes.
"He can die as well as we. Is he not flesh and blood?"
"He will never really die, though."
"Nor will we, Jo. But what does that avail us? I can't do without
him."
And she sobbed again, hopelessly.
"Perhaps it is not so had," said Johannes. "We will call in the
morning, and they surely will let us see him."
And so they talked on for a time. Then Johannes said:
62. "Let me stay with you, Marjon. It really seems as if I never again
could go away from you."
Marjon looked at him through her tears, and even smiled.
"But, Jo, we cannot do as we used to. We are no longer children. I
am already eighteen, and are you not that also?"
"Then let us become husband and wife, so that we can remain
together," said Johannes.
"Then you no longer love that other one more than me?"
"I think not, Marjon; for she would understand nothing of this, and
certainly would not join us in our sorrow."
"But, dear boy, we are far too young to become husband and wife."
"I do not understand, Marjon. First you find us too old to stay
together, and then you find us too young. And yet I want to remain
with you. How can it be done?"
"Listen, Jo. Formerly you said to me, 'No foolishness,' and that hurt
me for I cared much more for you than you did for me. Why were
you never more kind to me then?"
"Because I was forced to remember that ugly, dark woman, your
sister. I cannot bear the thought of her."
Marjon reflected a while, and then said:
"But that is no reason for you to be hard toward me, Jo. I am not
low, like her."
Johannes was silent. Then she resumed:
"But then I know what, Jo: you may stay here. But now I shall say
'No foolishness,' and remain unyielding until you shall have forgotten
that ugly woman. Will that do?"
63. "Yes, Marjon," replied Johannes. Then a pillow and some covering
were given him, and he lay on the hard floor of the little kitchen the
entire night. And now and then, as one of them became aware that
the other was still awake, they would talk together, softly, about
their poor friend, each trying to comfort the other.
And thus it happened, as I told you it would, that, before the ending
of the book, they became husband and wife.
But when Johannes forgot the ugly, dark woman Marjon's sister I do
not tell you; for that does not concern others.
XXIII
The humble little kitchen, in the first pale, glimmering light that
passed through the unwashed, uncurtained window; two rush-
bottomed chairs; the unpainted table with the oil-lamp and the
untidy coffee-set; Marjon's narrow iron bed, which quaked if she
merely stirred; her breathing, now deep and regular, for at last she
slept; the first chirping of the sparrows out-of-doors; continually
before Johannes' mental vision the pale face of his kind Brother,
befouled with blood and ashes; in his ears the powerful voice
resounding through the arches of the church; the howling of the
mob; and then—his own body, stiff and sore, on the hard, wooden
boards....
Then, all at once, light! Bright, golden sunlight, a mild, refreshingly
fragrant air, all pain away, an elastic, feather-light body—and the
majestic sound of the sea.
Where was he? Where—where!
Oh, he knew; he felt in himself where he was.
64. He recognized the feeling of self-consciousness, although he had not
recalled his surroundings.
But he heard the ocean—heard it roaring grandly as only it roars on
a level, sandy coast; and he heard the whistling of wind in the
rushes. And he watched the play of the grey-green waves as they
came rolling in—their long lines of shining breakers crested with
combing white, dashing and splashing and foaming over the flat
stretches of sand.
He had seen it all for years, and every day it was the same, from
age to age.
And when he glanced round to see if his little friend Wistik, whom he
hoped to find, was also here, he saw, close beside him, a bright little
figure sitting quite still and gazing out over the sea.
It was not Wistik. No, for this one had the large, gauzy wings of a
dragon-fly, and a little mantle of delicate blue waving gently in the
sea-breeze.
"Windekind!" exclaimed Johannes.
Then the bright being looked at him, and he recognized the dear,
enigmatical eyes, and the exquisite hair—a bloom-like blonde like
the mere sheen of gold—with its flower-crown of green and white.
"Here we are again," said Windekind.
"Then did you not die with Father Pan?" asked Johannes, in
astonishment.
"I live forever," said Windekind.
Johannes thought this over. He was tranquil again, as he always was
here. Life, so rude and painful, seemed now very far away. He felt
only calmness and contentment, although he well knew that his
body still lay on the hard floor.
Then he asked, "Does not that bore you?"
65. Windekind laughed, and held out in front of him his flower, which he
used as a staff. It was not an iris, but a strange, splendid blossom—a
lily or an orchid—blue, striped with white and gold.
"Silly boy!" said he. "To be bored is to be no longer able to enjoy
anything. I am not a human being, that gets bored after a few
years. I am not weary of happiness."
"Never?" asked Johannes.
"That I do not know," answered Windekind; "but not yet. If life were
to bore me, then I should die and return to my Father. He can never
grow weary."
"And have you grown still wiser?"
Windekind looked tenderly and very seriously at Johannes.
"Do you see my flower?" he asked. "This is not my old iris. This is
much more beautiful. Oh, Mother Earth is greatly changed; and so
am I."
Johannes looked about him. But everything appeared as before: the
long lines of delicate green dunes; the sky, all mottled with white
clouds; the graceful sea-gulls rocking in the wind, with their cry of
grand and lonely liberty. But on the water not a sail was to be seen,
nor on the strand a person.
"How good it is to see you again," said Johannes. "I have been so
sorry about Father Pan. And now I am very anxious about my poor
Brother."
But as Johannes said this he felt quite calm and peaceful; and this
puzzled him.
Windekind looked at him, and smiled mysteriously.
"That was a long time ago," he said.
And when Johannes gazed at him in amazement, he repeated:
66. "Long ago—quite a thousand years."
"A thousand years?" murmured Johannes, mistrustfully.
"Yes, truly a thousand years," said Windekind, positively. "I have
grown old, although you cannot see it in me. But the longer those of
my race live, the younger they grow, in nature and appearance.
Learn that yourself, Johannes—it is well to. I have grown stronger
with the centuries, and more elastic—wiser and more loving. That's
the way. I have not now an enemy upon earth. I have made up with
that small goblin Wistik. He is a right good fellow, after all."
"Is he not?" exclaimed Johannes, delighted. "I too have noticed
that."
"Yes," said Windekind, "when he has a leader. I have also become
reconciled to human beings."
"Oh, splendid, splendid!" cried Johannes. "I know who has done
that!"
"Right!" said Windekind, nodding. "Your good Brother did it."
Then Johannes saw great numbers of sea-gulls flocking together
from all sides, wheeling and screaming because of something in the
distance that was drawing nearer from out over the sea. It was like a
large bird soaring on vast, silently outspread wings. The fierce
sunlight fell upon it, making it flash like burnished gold, or like some
shining metal. As it came nearer Johannes saw that it had the pretty
colors of a swallow, steel-blue, brown and white, but with gilded
beak and claws, and that long, variegated feathers, or ribbons, were
streaming out behind, because of its rapid flight. The exquisite white
of the circling, screaming sea-gulls was in sharp contrast with the
huge, dark-colored hulk. A soft, clear sound came from above, as of
clinking glass attuned like bells.
"What is that immense creature?" asked Johannes; for the shadow
of it moved over the sea like that of a cloud.
67. "That is not a creature," replied Windekind. "There are human
beings in it, but they are not at all ugly now, nor ridiculous. Only
look!"
And Johannes saw, from its immobility, that it was not a bird, but a
colossal air-ship in the form of a bird. And also he could see, clearly,
that lightly dressed figures were moving to and fro along the decks,
tossing crumbs to the sea-gulls that, fluttering, and crying caught
them up.
Then the great shining wings altered their course, and with a
graceful movement the colossus dipped gently downward, skimming
the level sandy beach for the distance of a hundred yards.
At last it was still, and Johannes could admire the splendid structure:
the glittering gold, the gleaming steel-blue decorations, and the
bright-hued banners and pennants with gold-lettered mottoes that
fluttered in the breeze.
"Climb up," cried Windekind, "it is going away again. It will not stay
a great while."
"Are you going along?" asked Johannes.
"Yes," replied Windekind. "I am at home with these people. But
remember they cannot see us yet, any more than could those a
thousand years ago. They are still only human beings."
Johannes, his hand in Windekind's, floated up to the air-ship, and
nestled in the golden crown upon the head of the bird. Secluded
there, they could see what the people were doing.
The people were strong and handsome, like those in the realms of
Father Pan; but their hair was darker, and their faces, with
thoughtful eyes, were more earnest. And they all resembled
Johannes' Brother—as if they were all one large family, and akin to
him.
68. The garments of all of them were much alike—exceedingly simple.
They were of unfigured material, similar to linen, with the pretty,
sober coloring of some birds—the wood-dove and the peregrine; and
all were bordered with fine, bright-colored embroidery. Almost
without exception the passengers carried flowers. And festoons of
flowers hung in every part of the ship; but these were wilted, and
diffused the sweet, keen fragrance of roses.
All went with heads uncovered, and their waving hair was thick, but
not long. There was little to distinguish the dress of the men from
that of the women; but the men all wore full beards, and the women
braids of hair wound about their heads.
Now, leaving their vessel for a short time, they raced along the
beach, laughing merrily, and glad of the exercise. Johannes saw that
they wore sandals—just like the man in brown at Roodhuis'; and he
had to laugh at the recollection. The younger ones were barefooted.
After they had bathed and played, they climbed into the ship again;
and, taking their places, all facing the sea, they sang a song.
Although Johannes did not understand the words, he knew the
meaning of them. It sounded like a psalm, but was more fine and
earnest than any he had ever heard.
"That is the song of thanks they always sing after a safe passage
over the great water," said Windekind. "Yes, they mean it, for they
all know the Father. See how they mean it."
And Johannes saw the deep emotion in their earnest faces, and the
tears that glistened beneath the eyes of the younger women. And he
heard the quiver of feeling in their full, pure voices.
Then the magnificent great bird, with a strange clatter of unfolding
wings, with the whirring of unseen wheels, and the klink-klank of
glass bells, rose slowly, and pointed its golden beak and its fixed,
crystal eyes toward the land.
"But how does it move?" asked Johannes.
69. "Could you have explained to your forefathers how an electric
vehicle of your own time was propelled?" asked Windekind. "Then
do not ask that question, but rather, take a look at your native
country, and see how beautiful it has become."
The long line of coast was visible as they ascended, and Johannes
could see extending into the ocean at regular distances great dikes
of dark-grey stone, over which the white foam of the waves was
splashing.
"They are not handsome, but necessary," said Windekind. "But here
are our dunes."
And behold! They were as fair and free as in the olden days—a wide,
open wilderness without hedge or fence, without shavings or paper.
The hollows were full of little green groves; and there the white
hawthorn blossomed, and the singing of hundreds of nightingales
ascended to their high position. Johannes saw, as of old, the little
white tails of thousands of rabbits, flipping over the grey-green
stretches of moss. And also he saw people—sometimes by twos or
threes, then in large groups. But they did not disturb the harmony of
the peaceful scene, and their delicate grey, soft brown, and subdued
green clothing was quite in keeping with the tender tints of the
landscape.
After that came the verdant country. And how excited Johannes was
when, in his flight, he saw it looking like one great, flowery, tree-
filled park!
The bright green fields were there, the straight ditches and canals;
but everywhere were trees. Sometimes they stood alone—mighty
giants casting broad shadows; sometimes in great forests, each one
vast expanse of foliage, cool and rustling, where the wood-doves
cooed, and golden thrushes whistled. Gorgeous blossoms and thickly
flowered shrubs, such as Johannes had seen only in gardens, were
everywhere—growing wild in such masses that, from above, they
sometimes looked like carpets of glowing red or deepest blue.
70. And the small white houses of the people, looking as if some giant
had sawed them out with supple hand, were dotted about in the
midst of the verdure and flowers. But on the borders of the water, by
lakes and rivers and canals, were they strewn most thickly. The
shining blue waters appeared to be the magnet which had attracted
the little square blocks.
"You see, indeed, Johannes," said Windekind, "it was their own fault
that human beings seemed out of place in Nature. They had no
reverence for her, and harmed her in their stupidity. They have now
learned from Nature how beautiful and like unto her they themselves
may be, and they have made friends with her. They have taught
their children, from their earliest infancy, to do no needless damage
to flower or leaf, and to kill no creature ruthlessly; taught them also
to desire to be worthy of their place in the midst of all those
beautiful and charming objects. Sacred reverence for all that is
beautiful, and for everything that has life, is now strictly enjoined.
Thus is peace preserved between man and Nature, and they live in
intimate relations, neither annoying the other."
"But, Windekind, where are the cities? I see only scattered houses
and churches. And where are the iron railways and their sooty
stations? And where are the factories, with their tall chimneys and
dirty smoke?"
"My dear Johannes, ought ugly things to be retained any longer than
extreme need for them demands?"
"Are not, then, railroads and cities and factories necessities?"
"There are still factories, but they do not have to be ugly. There they
are—finer than many palaces of a thousand years ago. And why
tracks of iron, when the broad ways of the air are open and free to
all? And why swarm in cramped quarters, high over one another, so
long as there is dwelling-room amid the flowers and the verdure?
Men were not so stupid but that they found a way to dispense with
71. all that ugliness, and to drive their engines without the burning of
dusty, deeply buried coal. But still some roads remain. Look!"
And Johannes saw that all the dwellings were connected by roads—
some of them fourfold and broad, of a dark russet color; others like
narrow white ribbons winding through the grass from house to
house. And people were passing over them, afoot, or in small,
swiftly moving vehicles.
"It is a holiday," said Windekind. "Such days are now really happy
and holy days, without the deadly dreariness of the former ones."
Everywhere Johannes saw little churches having pointed spires in
the old Dutch style; but now they were full of statuary and
ornament. The doors stood open, and people were passing through.
And now Johannes heard the sound of music coming out of those
little churches—as pure and as fine as the best he had ever heard.
"Oh, Windekind, how I should love to go in and listen to that
splendid music! I do so want to," said Johannes.
But Windekind put his finger to his lips, and said:
"Hush! We are going to hear still better. Our voyagers are going to a
much larger church, where most beautiful music can be heard. They
are pilgrims, such as go from all countries every year, at this time, to
celebrate the great festival."
"Do I not see another air-ship, Windekind? And there—still another?"
asked Johannes.
"Yes; perhaps, indeed, one may be going along with us," said
Windekind. "That will make it lively."
And very soon there actually came a second air-ship—a big brother-
bird, that flew up to them. Then the flags dipped, and wide dark-
blue banners, bearing silver-lettered mottoes, were unfurled to the
breeze. The people waved, and shouted aloud. And when the twin
birds were so close together that the tips of their great bright wings
72. nearly touched, the people on Johannes' ship struck up an anthem—
a full and powerful song—that was immediately responded to by an
antistrophe from the other ship. And thus they took turns, first one,
then the other, for quite a time.
Johannes' heart was warmed by this sweet understanding among
peoples wholly unknown to one another.
"Do all men now speak the same language?" he asked his friend.
"Do you not hear what they are singing? All people have chosen that
language as the most beautiful and the most natural. It is Greek."
"I do not know Greek," said Johannes, regretfully.
"But just look at that pennant, then, on the other ship. What does it
say?"
"That is Dutch, Windekind—ordinary Dutch," cried Johannes. And he
read: "There is no Death," and "Gladness only endures." And he also
read the name of the ship, "he Heron."
Then his own ship dropped down again, upon a level meadow close
beside some large buildings of grey freestone, charmingly
sculptured, and there, for some mysterious reason, the vessel lay a
long while—to get up power, thought Johannes. And the pilgrims
took advantage of the delay to dance over the meadows with
graceful steps, and also to replace with fresh flowers the wilted
festoons.
Then they rose again, and whizzed through the still, summer air
toward the south. Johannes noticed that not much more than half
the land was devoted to field and orchard and vegetable-garden,
and that all the rest was forest and park and flower-garden; that
there were no hedges nor fences, nor any walls, except those
against which grapes and peaches were growing. He did indeed still
see brown and white sails on lake and river—that beautiful and ever
charming spectacle—but there were no more of the tall four-armed
windmills. And that was a pity.
73. "One cannot demand everything," said Windekind.
Johannes saw colossal wheels, like anchored paddle-wheels,
glistening in the sunlight—turning constantly, and moved by some
mysterious force. That certainly was better than smoking chimneys.
And nowhere was it dirty, nowhere was there wan poverty, nowhere
the deathly ugliness and monotonous melancholy of the cities. He
saw no ragged nor wretched people, no unsightly regions of refuse
and lumber. In the places where he knew the cities to have been,
there were now verdant tracts vocal with the songs of birds, and
fruitful, well-tilled fields and gardens.
"The housekeeping of the world is revolutionized, dear Johannes,"
said Windekind. "It lasted quite a while, and cost considerable
bickering; but that is all over now, and everything is according to
method. I myself take real pleasure in it."
And from his golden seat he gazed over the country, like a tiny
pretty king, who, proud and well-satisfied, rules his domain with a
floral sceptre.
"Watch, now: we are going higher. We have to fly over the
mountains."
And the ship rose until the people below were no longer visible, and
at last even the houses disappeared. It grew chilly as they cut
through the white mists of the great clouds; and, as of old,
Windekind threw his little blue mantle about Johannes. Thus they
went on for hours, in fog and mist, and the mighty vessel quivered
with the speed of its flight. The voyagers were still, and stayed, snug
and safe, inside. On they rushed, through rain and through snow,
catching occasional glimpses of wide tempestuous landscapes, with
green fields, foaming rivers, snow-capped mountains, glaciers, and
lakes of gleaming blue.
"Is the whole world as beautiful now, and as well cared for, as my
own country?" asked Johannes.
74. "The work of men is never complete," replied Windekind, "and that
is good for them, else they would become too proud. Asia and Africa
are a long way yet from being in trim, possibly they never will be.
But then it is all very well as it is—very well. A thousand years ago
one could not have said that."
How long they had been speeding thus, Johannes could not say. It
seemed to him many hours. Then the great billows of cloud grew
more and more transparent, and again the green land beneath them
became visible, and also a deep, deep blue sea.
"Is it Italy?" asked Johannes. Windekind nodded, and Johannes
hoped they would stay still a while so that he might see the beautiful
country of which the priest had told him. Then the ship descended
until people and houses could again be distinguished, and Johannes
saw a scene so grand, so rich, so overwhelming, that he was startled
and almost speechless. He could only say, thinking of Marjon, "Oh,
how shall I describe all this?"
For the scene was exhibited with a fulness and variety that left no
time for close observation. It was a landscape and a world-city in
one—an extraordinary valley, down which the vessel now drifted, full
of trees, verdure, flowers, buildings, statues, and people. Just before
him he saw a gigantic azalea-tree covered with red flowers; farther
on, a long arcade, overgrown with ivy, extending down to the foot of
the vale. Then a temple with tall, slender, white pillars, also
overgrown with ivy. In the middle of the valley stood a colossal piece
of sculpture—simply a head. Johannes saw the sun shining upon it.
And farther on there were structures unending, and thousands and
thousands of people. Altogether, it gave him an impression of
happiness and of beauty indescribable. Johannes could only cry,
"How splendid! How splendid!" doing his utmost to take in
everything, that he might remember and describe it to Marjon. But
he felt that it would be beyond his powers, and so deeply moved
was he by the beauty of the scene that he cried out, "It is too
glorious! I cannot bear it!" And he wondered if the ship was going to
stop there.
75. It did not stop, but floated farther on—not far now from the ground
—and followed the rocky coast. Johannes remembered the red rocks
and the coast where he and Wistik had sat when the Devil appeared.
This country, also, looked well-tilled and inhabited, after the manner
of his own country.
Then they put out again, over the blue, deep sea, and observed how
it was navigated by large, swift vessels, without either sail or steam.
They seemed to glide over the water as sledges over the snow, and
the white foam flew high up over the bows.
Then after a long voyage there loomed from the sea, like a violet
shadow, a large island; and, although it was broad daylight, it
seemed as if above that island a bright yellow-white star were
sparkling.
"That is our goal," said Windekind. "Take heed, now, you are going
to see something fine."
And when they came nearer, Johannes could not tell what it was:
whether the island was Nature's work, or some marvel wrought by
the hand of man.
For that whole great island, that from a distance had looked like a
mountain, appeared, when approached, to be entirely covered with
buildings—a piling up of pillars and roofs that soared one above
another, and converged to an awe-inspiring dome. That crowning
dome sparkled in the clear, sunlit air like an arrested cloud—with the
silvery, light green, and dark blue splendor of a glacier covered with
thousands of beautifully sculptured, inverted icicles; and upon the
top shone the yellow-white light which, even in broad daylight,
seemed to be a star.
So immense and so numerous were the structures, that one could
not tell what the natural form of the island had been, nor what had
76. been made by human hands.
Coming still nearer, one could see green masses of foliage filling all
the spaces between the buildings, up to the very top. The whole
island seemed a miracle of art and nature; of columns of pure white,
of silver and silver-blue; of cupolas, bronze-green or golden; while
amidst them all was the dark green of the dense groves and the
shrubbery, above which rose the tufted palms on their slender,
slightly curved stems.
"Oh, Windekind," cried Johannes, "is this a story?"
"This is a story," said Windekind, "as fine as any I ever told you. But
this one is true. Human beings first heard of it through me, and then
they resolved to build it as soon as they could find time, and
housekeeping was systematized. It could have been somewhat finer,
but still it came out very nicely, especially when you reflect that they
have had merely a hundred years in which to work out the plan;
considering, also, that, when half completed, an earthquake
destroyed it."
"What is it that glitters on that high dome at the summit of the
island? It looks like a distant star. Is it fire?"
"That is not fire, Johannes, but metal—a golden flame. It is a piece
of gilded metal, that always glow's in the sunlight as if it were
burning. By means of that flame the people wish to indicate their
ardent love."
"Love for whom, Windekind—for one another, or for God?"
"They know no difference, Johannes," said Windekind.
With radiant faces the pilgrims stood gazing at the spectacle; and,
shouting their joy, they sang again. Only a few of the older ones
appeared to have seen the island before.
The sea was now covered with large white vessels speeding to and
fro, and one could also see air-ships flying thither from all points of
77. the compass, like herons to their nesting-place.
Then Johannes vessel settled down upon a great grassy plain close
to the shore, and the pilgrims alighted. They were embarrassed and
bewildered now by all that surrounded them—by the multitude of
air-ships, and also by the people, among whom they felt shy and
strange.
Hundreds of these ships were now at rest—a brilliant spectacle, all
differently rigged and adorned, and patterned after various birds.
There were hawks and eagles, and giant beetles, entirely of bronze,
looking like gold. There were moths of green-reflecting metal; and
dragon-flies with wings of iridescent glass; wasps with bodies ringed
with black and yellow; butterflies having enormous yellow wings,
marked with peacock-eyes of blue, from which long pennants, black
and red, streamed out behind.
There was now considerable commotion throughout the grassy plain,
among those who, just arrived, were trying to find their way.
On the coast, around the whole island, was an almost unbroken
series of cool terraces beneath white colonnades shaded by the light
lavender flowers of the glycine; and behind them were small, white-
stuccoed recesses overlooking the sea. There the hundreds of
thousands of pilgrims who annually came to the feast were lodged
and fed.
Johannes saw them sitting at long tables on which were bread, fruit,
and flowers. And above the sound of the foaming surf, as the
crystalline blue water broke in white spray over the dull red rocks,
cheerful talking and laughing could be heard, and also the music of
guitars.
Higher up, the island was clear and open. Here were sunny parks
with low flowering shrubs, and now and then a tall palm, and
everywhere temples and buildings for various purposes.
78. With his hand in Windekind's, Johannes glided over this, unable to
note all of the many things that met his gaze. He saw, beneath him,
close to the shore, large arenas for the games and the races; also
long buildings, with thousands of columns, for the display of useful
and ingenious articles and implements.
A little higher were gardens with plants and animals, museums,
observatories, immense libraries, and covered colonnades and
assembly-rooms for scholars. After that came theatres, in Hellenic
form—semicircular—with white marble seats. And every place was
thronged with people, in their tasteful, charming dress. The brown
and the yellow races were represented; also the very dark-colored
ones, with their flashing eyes, haughty bearing, and vigorous
frames. These wore brightly-colored silken garments, green and red,
embroidered with gold; but all who were white or fair were soberly
clad in soft, refined colors.
Still higher were collections of statues, marble and gilded—many of
them outside in the park, among the flowers, the aloes, and the
plashing fountains; others, beneath long porticoes; and in large, low
buildings there were sketches and paintings, or statuettes wrought
in metal or carved in wood.
Finally, still higher up the incline, close beside the great middle
temple which was the crown of the island, surrounded by the serious
silences of dark laurel and myrtle groves, were the temples of music.
There was a variety of them. Some were lighter and more
ornamental—of brighter stone, and with steep, golden roofs; others,
massive and strong, of quiet grey limestone, with green and red
granite pillars, and arched roofs of bronze.
Windekind pointed out that each temple was dedicated exclusively to
one composer; and Johannes heard with joy names that were well
known to him in his own day.
"Which one shall we choose?" asked Windekind. "Nowhere else upon
earth can their works be heard as in any one of these temples."
79. While he hesitated, with the name Beethoven on his lips, Johannes
saw coming over the grassy path between the rose-colored flowering
oleanders, a group of five majestic persons. They were tall, powerful
figures—four men and a woman. The men were all elderly, one of
them having silver-white, the others thick grey hair. The woman was
younger, and indescribably noble and beautiful. They each wore a
mantle of the same amaranthine red, and upon the head a small
wreath of green myrtle, and each one held a flower.
They walked slowly and with dignity, and wherever they went the
people all greeted them. Those who had been chatting were
respectfully silent; those sitting or lying down stood up; and those
who were in their path hastily stepped aside.
"Who are those five people, Windekind?"
"They are the five kings. Do you not see that they carry my flower in
their hands? It is the blue, white, and gold Lily of the Kings, which
the people have evolved. Formerly it did not exist. These are the
noblest, wisest, strongest, the purest and most worthy among
human beings. In them are united, in most perfect harmony, all of
the human faculties. They are poets, masters of speech, and sages,
that purify and elevate morals. They are regulators of labor, directors
in business, in taste, and in science. Not all are equally excellent, nor
are there always so many. The best are sought for and elevated. But
they bear no rank—they have no court, no palace, no army, no
realm. Their throne is where they seat themselves; their kingdom is
the whole world. Their power consists in the beauty of their words,
in their wisdom, and in the love of their fellowmen. See how they
are revered! Look at those adoring women—doing obeisance as ever.
There are still the very same foolish ones among the young women."
And Windekind called Johannes' attention to the fair enthusiasts who
attempted not only to kiss the hands of the Five, but also to touch
them with their flowers, which, thereby made sacred as relics, were
later to be cherished as mementoes. But the sages smilingly
motioned these aside, and entered the largest of the music-temples
80. —a mighty structure of smooth, cream-white marble, without
ornament, but pure in line, and nobly harmonious in its proportions.
It was round in form, having a bronze roof without side-windows,
and lighted only from above. Over the entrance, in large gold letters,
was the name "Bach."[1] When the Five came in all the people stood
up, and waited until they were seated in the chairs reserved for
them.
And then Johannes heard exceedingly fine music. And Windekind
said, "This fountain is not yet exhausted, nor will it be for ages to
come."
When they were again out-of-doors, and Johannes saw the
happiness of all those beautiful people, and the mood of solemn
devotion into which the music had put them, he suddenly became
depressed, and said: "Oh, Windekind, now that I have seen all this,
and know what it is possible for people to be if only they are wise
and good, what avails it all when I have to return to that pitiful land
of ugliness and folly and injustice? And, alas, of what advantage is it
to all those poor people who are perhaps preparing for this lovely
life, but who yet are never to see it?"
Johannes looked imploringly at his friend, who was silently
meditating while they slowly drifted still higher along a dense grove
of dark laurel, through which the happy, high spirited people were
proceeding to the great, the loftiest temple.
Said Windekind: "You do not yet comprehend the unity of life,
Johannes. However beautiful all this appears to you, it is only a short
step in advance. These are yet, and will continue to be, human
beings—subject to illness and death, to quarrels and
misunderstandings, to superstition and injustice. All that now seems
to you elevated and marvelous is but a wisp of straw compared with
the magnificence of the Father to whom we all return. The victory is
not here, but higher. And whoever has made preparation, however
humble, shall have his rightful part in the final triumph."
81. Johannes did not fully understand, but eagerly drank in the comfort
of these mysterious words. Still musing upon them, he stepped out
of the dark, leafy woods upon an extraordinary plain, and saw
before him the great middle temple that formed the summit of the
island.
The sight of it was overwhelming, for it was almost frightfully and
oppressively grand; and he saw all the oncoming people stop, as
though turned to stone. None ventured to speak unless in whispers.
The plain was so large that those who had just reached the border
of the woods could not distinguish the hands nor the heads of those
who were entering the temple. The plain was utterly bare—upon it
was neither plant nor statue. It was the leveled top of the natural
rock—a reddish-grey granite, smoothly polished, and rising gradually
by low flights of steps each twelve paces wide and one foot high.
The base of the temple was sombrely grand. Its shape was oblong,
the greatest length being from north to south, showing an endless
series of massive lotus-columns, close together, and all of the same
reddish-grey stone. The eye was bewildered by them, as if in a dark
forest of pillars. The steady stream of dot-like human forms
appeared to be engulfed in their shade.
82. These mighty columns, resting on straight and flat string-courses,
supported a broad terrace that surrounded the entire temple. Upon
this terrace was a layer of earth, whence sprang a luxuriant growth
of trees and shrubs, wide-spreading sycamores, towering cypresses,
and slender palms—all overgrown and bound together by a veil of
flowers and leafy vines.
Then succeeded, higher up, a second series of pillars, supporting
another terrace covered with smaller shrubs. And above that, still a
third, whose columns were of brighter stone—light-green and grey.
The topmost row was of pure white, against which the green of the
plants was in clear relief.
And above these, delicate and daring, soared a convergence of
groinings, with a maze of exquisite spires and pinnacles, resembling
a forest of stalagmites. Together they formed an oval whose chief
colors—steel-blue, dark and sparkling, light-grey, and silver—
resembled a cloud or a glacier; yet all harmoniously fashioned by
human hands. Above, on a colossal tripod, glowed the emblem of
love and life—the Golden Flame!
Although thousands of people from every side were ceaselessly
pouring into the temple, and disappearing amid the dark columns, it
was very still there—so still that above the sound of moving feet one
could distinctly hear the babbling of the brooks that, coursing
through the verdant terraces, flowed thence to the four corners of
the plain.
Johannes tried to follow the soft speech of the people, but he did
not understand the language. Then Windekind, calling his attention
to a trio of persons—a vigorous father about fifty years of age, and
his two sons, slender, fine fellows not far from twenty—said, "Listen
to them!" It was Dutch they were speaking—pure, mellifluous Dutch.
The father said: "Look, Gerbrand; the lowest columns are so large
that ten men could not encircle them. But within the temple, in the
great oval centre, there are a hundred columns, far larger, that reach
83. to the floor of the third terrace. On the groined arches resting upon
those columns stand twice as many smaller pillars, which, rising
somewhat higher than the gallery of the third terrace, are attached
thereto by a system of buttresses. On these two hundred smaller
pillars rests the enormous middle dome which over-arches the oval
hall. The dome is entirely of metal. The dark blue is steel; the grey,
aluminium; the bright green, bronze. The pinnacles, arches, and
ornamentations are all of silver or silver-plated steel. In the four
corner-spaces, between square and oval, stand four towers, having
small gold-covered cupolas. Within these, elevators move up and
down, and through them the water also is raised for the terraces.
"The tall tripod at the top of the dome is of bronze, and the flame is
gilded bronze. The flame itself is twelve metres long, and its tip is a
hundred and eighty metres above the plain."
Gerbrand, the younger son, knitting his brows as he regarded the
awe-inspiring spectacle, asked: "How many people have worked
upon it, father?"
"Oh, more than a hundred thousand, for nearly a century. But if the
temple should again collapse, as once it did, ten times as many
more would eagerly come, to rebuild it in less than half that time."
Drawing nearer, Johannes discerned, on the stone band beneath the
first terrace, colossal silver letters, in plain Roman form. On the front
a portion of a proverb was legible. The rest of it probably ran around
the entire temple. Johannes retained the majestic tenor of it,
although he did not comprehend the full meaning. Facing him was:
REDEUNT SATURNIA REGNA
and on the eastern side he read the first words,
IAM NOVA PROGENIËS....
This was all he could distinguish.
84. Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com