100% found this document useful (1 vote)
15 views

The First Line of Code: Android Programming with Kotlin Lin Guo - Quickly download the ebook to explore the full content

The document introduces 'The First Line of Code: Android Programming with Kotlin' by Lin Guo, a comprehensive guide designed for both beginners and professionals in Android development. It covers essential topics in Android and Kotlin, structured in a way that allows readers to start from any chapter based on their existing knowledge. The book also includes practical exercises and resources to enhance the learning experience.

Uploaded by

doyinmarggi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
15 views

The First Line of Code: Android Programming with Kotlin Lin Guo - Quickly download the ebook to explore the full content

The document introduces 'The First Line of Code: Android Programming with Kotlin' by Lin Guo, a comprehensive guide designed for both beginners and professionals in Android development. It covers essential topics in Android and Kotlin, structured in a way that allows readers to start from any chapter based on their existing knowledge. The book also includes practical exercises and resources to enhance the learning experience.

Uploaded by

doyinmarggi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.

com

The First Line of Code: Android Programming with


Kotlin Lin Guo

https://ebookmeta.com/product/the-first-line-of-code-
android-programming-with-kotlin-lin-guo/

OR CLICK HERE

DOWLOAD EBOOK

Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com


Lin Guo

The First Line


of Code
Android Programming with Kotlin
Translated by
Litao Shen
The First Line of Code
Lin Guo

The First Line of Code


Android Programming with Kotlin
Lin Guo
STCA WebXT Edge Mobile
Microsoft
Suzhou, Jiangsu, China

ISBN 978-981-19-1799-8 ISBN 978-981-19-1800-1 (eBook)


https://doi.org/10.1007/978-981-19-1800-1

Jointly published with Posts & Telecom Press


The print edition is not for sale in Mainland China. Customers from Mainland China please order the print
book from: Posts & Telecom Press

© Posts & Telecom Press 2022


This work is subject to copyright. All rights are solely and exclusively licensed by the Publisher, whether
the whole or part of the material is concerned, specifically the rights of reprinting, reuse of illustrations,
recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission
or information storage and retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication
does not imply, even in the absence of a specific statement, that such names are exempt from the relevant
protective laws and regulations and therefore free for general use.
The publishers, the authors, and the editors are safe to assume that the advice and information in this
book are believed to be true and accurate at the date of publication. Neither the publishers nor the
authors or the editors give a warranty, express or implied, with respect to the material contained
herein or for any errors or omissions that may have been made. The publishers remain neutral with
regard to jurisdictional claims in published maps and institutional affiliations.

This Springer imprint is published by the registered company Springer Nature Singapore Pte Ltd.
The registered company address is: 152 Beach Road, #21-01/04 Gateway East, Singapore 189721,
Singapore
Preface

Phew, what a huge project!


Allow me to introduce myself. I am Lin Guo and am an Android developer from
China. I started Android development in 2010 and became an Android GDE in 2020.
Currently, I work for Microsoft.
The First Line of Code is my only book and incorporates my years of experience
in Android development. This is the best-selling Android book in China and has
helped tens of thousands of Chinese readers to start their Android development
journey.
However, I have never thought that this book could become international and I
appreciate the recognition from Springer.
I want to give special thanks to Litao Shen who is the translator of this book. He is
a software engineer in Meta Inc. Although we have never met personally, we became
friends because of this book. He mentioned that this book helped him to prepare the
interview for Facebook back then in the feedback for this book. Thus, when I started
the exploration for an English translator for this book, he immediately accepted this
offer and challenge. Thanks for your hard work in such a short time.
Now, you are reading the newest version of The First Line of Code. It covers most
of the important topics of Android and Kotlin. I hope you can read this book
carefully as more learning means more happiness. Enjoy it!

Target Audience

This book is not obscure and goes from easy to more complicated. It can help both
beginners and professionals. You do not need to know anything about Android or
Kotlin; however, some fundamental knowledge about Java helps smooth the learn-
ing curve as all the codes in this book are written in Kotlin which is based on Java.
You can start with any chapter in this book based on your condition as each
chapter is self-contained. If you are a beginner, it is recommended to start from

v
vi Preface

Chap. 1 to ensure a smooth learning experience. If you already grasp some funda-
mental Android knowledge, you can pick whichever chapters that interest you. I
recommend that do not miss the practice and Kotlin class section at the end of each
chapter.

Content Summary

As aforementioned, this book systematically covers essential Android development


knowledge and ensures that the difficulty level is in ascending order. There are
15 chapters in this book which cover four main components, UI, fragment, data
persistence, multimedia, networks, architecture, etc. for Android. For Kotlin, this
book covers fundamental syntaxes, tips, high-order functions, generics, coroutine,
DSL, etc. To make sure you can use them collectively, at the end of this book, we
will create a weather app, build and publish an open-source library.
Besides these, Chaps. 6, 9, 12, and 15 cover Git knowledge and you cannot miss
them if you want to learn Git.
Each chapter in this book is relatively isolated and independent, thus you can also
use this book as reference material.

Learning Resources

Download link: https://file.ituring.com.cn/Original/2004fe62f809edc265f6


Hope you all enjoy the reading!

Suzhou, Jiangsu, China Lin Guo


8 February 2022
Contents

1 Your First Line of Android Code . . . . . . . . . . . . . . . . . . . . . . . . . . 1


1.1 Android: An Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.1.1 Android System Architecture . . . . . . . . . . . . . . . . . . 2
1.1.2 Released Versions . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.3 What’s Special for Android Development? . . . . . . . . . 4
1.2 Set Up Development Environment Step by Step . . . . . . . . . . . 5
1.2.1 Prerequisite Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.2 Set Up the Environment . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Creating Your First Android Project . . . . . . . . . . . . . . . . . . . . 6
1.3.1 Creating HelloWorld Project . . . . . . . . . . . . . . . . . . . 7
1.3.2 Starting Emulator . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.3.3 Running HelloWorld . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3.4 Analyzing Your First Android Project . . . . . . . . . . . . 11
1.3.5 Resources in a Project . . . . . . . . . . . . . . . . . . . . . . . . 23
1.3.6 File of build.gradle . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.4 Mastering the Use of Logging Tools . . . . . . . . . . . . . . . . . . . . 28
1.4.1 Using Android Log Tool . . . . . . . . . . . . . . . . . . . . . . 28
1.4.2 Log Vs Println() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2 Explore New Language: A Quick Introduction to Kotlin . . . . . . . . . 33
2.1 Introduction to Kotlin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.2 How to Run Kotlin Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.3 The Foundation of Programming: Variables and Functions . . . . 38
2.3.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.3.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
2.4 Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
2.4.1 if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
2.4.2 when Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
2.4.3 Loop Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

vii
viii Contents

2.5 Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . 52


2.5.1 Class and Object . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
2.5.2 Inheritance and Constructor Function . . . . . . . . . . . . . 54
2.5.3 Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
2.5.4 Data Class and Singleton . . . . . . . . . . . . . . . . . . . . . 62
2.6 Lambda Expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
2.6.1 Creation and Iteration of Collection . . . . . . . . . . . . . . 66
2.6.2 Functional APIs of Collections . . . . . . . . . . . . . . . . . 69
2.6.3 Java Functional API . . . . . . . . . . . . . . . . . . . . . . . . . 73
2.7 Null Safety . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
2.7.1 Nullable Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
2.7.2 Nullability Check Tools . . . . . . . . . . . . . . . . . . . . . . 78
2.8 Kotlin Tricks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
2.8.1 String Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . 82
2.8.2 Function Default Arguments . . . . . . . . . . . . . . . . . . . 83
2.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
3 Start with the Visible: Explore Activity . . . . . . . . . . . . . . . . . . . . . . 87
3.1 What Is Activity? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
3.2 Activity Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
3.2.1 Manually Creating Activity . . . . . . . . . . . . . . . . . . . . 88
3.2.2 Creating and Mounting the Layout . . . . . . . . . . . . . . 90
3.2.3 Registering in AndroidManifest File . . . . . . . . . . . . . 92
3.2.4 Using Toast in Activity . . . . . . . . . . . . . . . . . . . . . . . 95
3.2.5 Using Menu in Activity . . . . . . . . . . . . . . . . . . . . . . 98
3.2.6 Destroying an Activity . . . . . . . . . . . . . . . . . . . . . . . 101
3.3 Using Intent to Communicate Between Activities . . . . . . . . . . 102
3.3.1 Explicit Intent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
3.3.2 Implicit Intent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
3.3.3 More on Implicit Intent . . . . . . . . . . . . . . . . . . . . . . . 108
3.3.4 Passing Data to the Next Activity . . . . . . . . . . . . . . . 112
3.3.5 Return Data to the Last Activity . . . . . . . . . . . . . . . . 113
3.4 Activity Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
3.4.1 Back Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
3.4.2 Activity States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
3.4.3 Activity Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
3.4.4 Explore the Lifecycle of Activity . . . . . . . . . . . . . . . . 118
3.4.5 Recycling Activity . . . . . . . . . . . . . . . . . . . . . . . . . . 125
3.5 Launch Mode of Activity . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
3.5.1 Standard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
3.5.2 singleTop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
3.5.3 singleTask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
3.5.4 singleInstance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
3.6 Activity Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
3.6.1 Identifying the Current Activity . . . . . . . . . . . . . . . . . 134
Contents ix

3.6.2 Exiting the App from Anywhere . . . . . . . . . . . . . . . . 135


3.6.3 Best Practice to Start Activity . . . . . . . . . . . . . . . . . . 137
3.7 Kotlin Class: Standard Functions and Static Methods . . . . . . . . 138
3.7.1 Standard Functions: with, run, and apply . . . . . . . . . . 139
3.7.2 Define Static Methods . . . . . . . . . . . . . . . . . . . . . . . . 142
3.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
4 Everything About UI Development . . . . . . . . . . . . . . . . . . . . . . . . . 147
4.1 How to Create UI? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
4.2 Common UI Widgets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
4.2.1 TextView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
4.2.2 Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
4.2.3 EditText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
4.2.4 ImageView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
4.2.5 ProgressBar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
4.2.6 AlertDialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
4.3 Three Basic Layouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
4.3.1 LinearLayout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
4.3.2 RelativeLayout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
4.3.3 FrameLayout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
4.4 Customize the Widgets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
4.4.1 Include Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
4.4.2 Create Customized Widgets . . . . . . . . . . . . . . . . . . . 182
4.5 ListView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
4.5.1 Simple Demonstration of ListView . . . . . . . . . . . . . . 185
4.5.2 Customize ListView UI . . . . . . . . . . . . . . . . . . . . . . 186
4.5.3 Optimize the Efficiency of ListView . . . . . . . . . . . . . 189
4.5.4 Click Event in ListView . . . . . . . . . . . . . . . . . . . . . . 192
4.6 RecyclerView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
4.6.1 Basics About RecyclerView . . . . . . . . . . . . . . . . . . . 194
4.6.2 Scroll Horizontally and Waterfall Flow Layout . . . . . . 197
4.6.3 RecyclerView Click Event . . . . . . . . . . . . . . . . . . . . 202
4.7 Best Practice to Build UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
4.7.1 Create 9-Patch Image . . . . . . . . . . . . . . . . . . . . . . . . 204
4.7.2 Build Beautiful Chat User Interface . . . . . . . . . . . . . . 208
4.8 Kotlin Class: Lateinit and Sealed Cass . . . . . . . . . . . . . . . . . . 213
4.8.1 Lateinit Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
4.8.2 Optimization with Sealed Class . . . . . . . . . . . . . . . . . 216
4.9 Summary and Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
5 Support Phones and Tablets with Fragment . . . . . . . . . . . . . . . . . . 221
5.1 What Is Fragment? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
5.2 How to Use Fragment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
5.2.1 Basic Use of Fragment . . . . . . . . . . . . . . . . . . . . . . . 223
5.2.2 Add Fragment Dynamically . . . . . . . . . . . . . . . . . . . 227
x Contents

5.2.3 Back Stack for Fragment . . . . . . . . . . . . . . . . . . . . . . 230


5.2.4 Interaction Between Fragment and Activity . . . . . . . . 230
5.3 Lifecycle of Fragment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
5.3.1 Fragment State and Callbacks . . . . . . . . . . . . . . . . . . 231
5.3.2 Experiment with Fragment Lifecycle . . . . . . . . . . . . . 232
5.4 Dynamically Load Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
5.4.1 Use Qualifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
5.4.2 Use Smallest-Width Qualifier . . . . . . . . . . . . . . . . . . 237
5.5 Fragment Best Practice: A Basic News App . . . . . . . . . . . . . . 240
5.6 Kotlin Class: Extension Function and Operator Overloading . . 249
5.6.1 Extension Function . . . . . . . . . . . . . . . . . . . . . . . . . . 249
5.6.2 Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . 252
5.7 Summary and Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
6 Broadcasts in Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
6.1 Introduction to Broadcast Mechanism . . . . . . . . . . . . . . . . . . . 259
6.2 Receive System Broadcast . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
6.2.1 Dynamically Register BroadcastReceiver for Time
Change . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
6.2.2 Open App After Booting with Static Receiver . . . . . . 262
6.3 Send Customized Broadcast . . . . . . . . . . . . . . . . . . . . . . . . . . 267
6.3.1 Send Normal Broadcast . . . . . . . . . . . . . . . . . . . . . . 267
6.3.2 Send Ordered Broadcast . . . . . . . . . . . . . . . . . . . . . . 270
6.4 Best Practice of Broadcast: Force Logout . . . . . . . . . . . . . . . . 274
6.5 Kotlin Class: Higher-Order Function . . . . . . . . . . . . . . . . . . . 280
6.5.1 Define Higher-Order Function . . . . . . . . . . . . . . . . . . 280
6.5.2 Inline Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
6.5.3 Noinline and Crossinline . . . . . . . . . . . . . . . . . . . . . . 289
6.6 Git Time: The First Look of Version Control Tools . . . . . . . . . 293
6.6.1 Git Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
6.6.2 Create Code Repository . . . . . . . . . . . . . . . . . . . . . . 293
6.6.3 Commit Local Code . . . . . . . . . . . . . . . . . . . . . . . . . 295
6.7 Summary and Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
7 Data Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
7.1 Introduction to Data Persistence . . . . . . . . . . . . . . . . . . . . . . . 297
7.2 Persisting Through File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
7.2.1 Persisting Data in File . . . . . . . . . . . . . . . . . . . . . . . . 298
7.2.2 Read Data from File . . . . . . . . . . . . . . . . . . . . . . . . . 301
7.3 SharedPreferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
7.3.1 Save Data in SharedPreferences . . . . . . . . . . . . . . . . . 304
7.3.2 Read Data from SharedPreferences . . . . . . . . . . . . . . 307
7.3.3 Implement Remembering Password . . . . . . . . . . . . . . 308
7.4 SQLite Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
7.4.1 Create Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Contents xi

7.4.2 Upgrade Database . . . . . . . . . . . . . . . . . . . . . . . . . . 317


7.4.3 Add Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
7.4.4 Update Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
7.4.5 Delete Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
7.4.6 Query Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
7.4.7 Use SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
7.5 SQLite Database Best Practice . . . . . . . . . . . . . . . . . . . . . . . . 333
7.5.1 Transaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
7.5.2 Best Practice to Upgrade Database . . . . . . . . . . . . . . . 335
7.6 Kotlin Class: Application of Higher-Order Function . . . . . . . . 338
7.6.1 Simplify Use of SharedPreferences . . . . . . . . . . . . . . 338
7.6.2 Simplify Use of ContentValues . . . . . . . . . . . . . . . . . 340
7.7 Summary and Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
8 Share Data Between Apps with ContentProvider . . . . . . . . . . . . . . 345
8.1 Introduction to ContentProvider . . . . . . . . . . . . . . . . . . . . . . . 345
8.2 Runtime Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
8.2.1 Android Runtime Permissions in Depth . . . . . . . . . . . 346
8.2.2 Request Permission at Runtime . . . . . . . . . . . . . . . . . 349
8.3 Access Data in Other Apps . . . . . . . . . . . . . . . . . . . . . . . . . . 354
8.3.1 Basic Use of ContentResolver . . . . . . . . . . . . . . . . . . 354
8.3.2 Read System Contact . . . . . . . . . . . . . . . . . . . . . . . . 358
8.4 Create Your Own ContentProvider . . . . . . . . . . . . . . . . . . . . . 362
8.4.1 Create ContentProvider . . . . . . . . . . . . . . . . . . . . . . . 362
8.4.2 Share Data Between Apps . . . . . . . . . . . . . . . . . . . . . 368
8.5 Kotlin Class: Generics and Delegate . . . . . . . . . . . . . . . . . . . . 377
8.5.1 Basic Use of Generics . . . . . . . . . . . . . . . . . . . . . . . . 377
8.5.2 Class Delegation and Delegated Properties . . . . . . . . . 379
8.5.3 Implement Lazy Function . . . . . . . . . . . . . . . . . . . . . 382
8.6 Summary and Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
9 Enrich Your App with Multimedia . . . . . . . . . . . . . . . . . . . . . . . . . 387
9.1 Run Application on Phone . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
9.2 Notification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
9.2.1 Create Notification Channel . . . . . . . . . . . . . . . . . . . 389
9.2.2 Basic Use of Notification . . . . . . . . . . . . . . . . . . . . . 392
9.2.3 Advanced Topics in Notification . . . . . . . . . . . . . . . . 399
9.3 Camera and Album . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
9.3.1 Take Photos with Camera . . . . . . . . . . . . . . . . . . . . . 404
9.3.2 Select Images from Album . . . . . . . . . . . . . . . . . . . . 408
9.4 Play Multi-Media Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
9.4.1 Play Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
9.4.2 Play Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
9.5 Kotlin Class: Use Infix to Improve Readability . . . . . . . . . . . . 420
9.6 Git Time: Advanced Topics in Version Control . . . . . . . . . . . . 423
xii Contents

9.6.1 Ignore Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423


9.6.2 Inspect Modified Content . . . . . . . . . . . . . . . . . . . . . 424
9.6.3 Revert the Uncommitted Changes . . . . . . . . . . . . . . . 426
9.6.4 Check Commit History . . . . . . . . . . . . . . . . . . . . . . . 427
9.7 Summary and Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
10 Work on the Background Service . . . . . . . . . . . . . . . . . . . . . . . . . . 431
10.1 What Is Service? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
10.2 Android Multithreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
10.2.1 Basic Use of Thread . . . . . . . . . . . . . . . . . . . . . . . . . 432
10.2.2 Update UI in Worker Thread . . . . . . . . . . . . . . . . . . . 433
10.2.3 Async Message Handling Mechanism . . . . . . . . . . . . 435
10.2.4 Use AsyncTask . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
10.3 Basic Use of Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
10.3.1 Define a Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
10.3.2 Start and Stop Service . . . . . . . . . . . . . . . . . . . . . . . . 442
10.3.3 Communication Between Activity and Service . . . . . . 445
10.4 Service Life Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
10.5 More Techniques on Service . . . . . . . . . . . . . . . . . . . . . . . . . 450
10.5.1 Use Foreground Service . . . . . . . . . . . . . . . . . . . . . . 451
10.5.2 Use IntentService . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
10.6 Kotlin Class: Advanced Topics in Generics . . . . . . . . . . . . . . . 456
10.6.1 Reify Generic Types . . . . . . . . . . . . . . . . . . . . . . . . . 457
10.6.2 Application of Reified Type in Android . . . . . . . . . . . 459
10.6.3 Covariance and Contravariance . . . . . . . . . . . . . . . . . 461
10.6.4 Contravariance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
10.7 Summary and Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
11 Exploring New World with Network Technologies . . . . . . . . . . . . . 469
11.1 WebView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
11.2 Use HTTP to Access Network . . . . . . . . . . . . . . . . . . . . . . . . 471
11.2.1 Use HttpURLConnection . . . . . . . . . . . . . . . . . . . . . 472
11.2.2 Use OkHttp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
11.3 Parse XML Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
11.3.1 Pull Parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
11.3.2 SAX Parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
11.4 Parse JSON Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
11.4.1 JSONObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
11.4.2 GSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
11.5 Implementing Network Callback . . . . . . . . . . . . . . . . . . . . . . 491
11.6 The Best Network Lib: Retrofit . . . . . . . . . . . . . . . . . . . . . . . 494
11.6.1 Basic Use of Retrofit . . . . . . . . . . . . . . . . . . . . . . . . 494
11.6.2 Process Complex Interface Address . . . . . . . . . . . . . . 499
11.6.3 Best Practice for Retrofit Builder . . . . . . . . . . . . . . . . 502
Contents xiii

11.7 Kotlin Class: Use Coroutine for Performant Concurrent App . . 504
11.7.1 Basic Use of Coroutine . . . . . . . . . . . . . . . . . . . . . . . 504
11.7.2 More on Coroutine Scope Builder . . . . . . . . . . . . . . . 510
11.7.3 Simplifying Callback with Coroutine . . . . . . . . . . . . . 514
11.8 Summary and Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
12 Best UI Experience: Material Design in Action . . . . . . . . . . . . . . . . 519
12.1 What Is Material Design? . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
12.2 Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
12.3 Navigation Drawer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
12.3.1 DrawerLayout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
12.3.2 NavigationView . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
12.4 FloatingActionButton and Snackbar . . . . . . . . . . . . . . . . . . . . 534
12.4.1 FloatingActionButton . . . . . . . . . . . . . . . . . . . . . . . . 535
12.4.2 Snackbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
12.4.3 CoordinatorLayout . . . . . . . . . . . . . . . . . . . . . . . . . . 540
12.5 CardView Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
12.5.1 MaterialCardView . . . . . . . . . . . . . . . . . . . . . . . . . . 542
12.5.2 AppBarLayout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
12.6 Pull to Refresh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
12.7 Collapsible Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
12.7.1 CollapsingToolbarLayout . . . . . . . . . . . . . . . . . . . . . 553
12.7.2 Optimizing Using of System Status Bar . . . . . . . . . . . 560
12.8 Kotlin Class: Creating Utils . . . . . . . . . . . . . . . . . . . . . . . . . . 564
12.8.1 Find Max and Min in N Numbers . . . . . . . . . . . . . . . 565
12.8.2 Simplifying Use of Toast . . . . . . . . . . . . . . . . . . . . . 566
12.8.3 Simplifying Use of Snackbar . . . . . . . . . . . . . . . . . . . 568
12.9 Git Time: Advanced Topics in Version Control . . . . . . . . . . . . 570
12.9.1 Branch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
12.9.2 Work with Remote Repo . . . . . . . . . . . . . . . . . . . . . 572
12.10 Summary and Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
13 High-Quality Developing Components: Exploring Jetpack . . . . . . . 575
13.1 Introduction to Jetpack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
13.2 ViewModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
13.2.1 ViewModel Basics . . . . . . . . . . . . . . . . . . . . . . . . . . 577
13.2.2 Pass Param to ViewModel . . . . . . . . . . . . . . . . . . . . 579
13.3 Lifecycles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
13.4 LiveData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
13.4.1 LiveData Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
13.4.2 map and switchMap . . . . . . . . . . . . . . . . . . . . . . . . . 590
13.5 Room . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
13.5.1 Use Room to CRUD . . . . . . . . . . . . . . . . . . . . . . . . . 596
13.5.2 Room Database Upgrade . . . . . . . . . . . . . . . . . . . . . 603
13.6 WorkManager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
xiv Contents

13.6.1 WorkManager Basics . . . . . . . . . . . . . . . . . . . . . . . . 607


13.6.2 Handling Complex Task with WorkManager . . . . . . . 608
13.7 Kotlin Class: Use DSL to Construct Specific Syntax . . . . . . . . 610
13.8 Summary and Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
14 Keep Stepping Up: More Skills You Need to Know . . . . . . . . . . . . . 619
14.1 Obtaining Context Globally . . . . . . . . . . . . . . . . . . . . . . . . . . 619
14.2 Passing Objects with Intent . . . . . . . . . . . . . . . . . . . . . . . . . . 622
14.2.1 Serializable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
14.2.2 Parcelable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623
14.3 Creating Your Own Logging Tool . . . . . . . . . . . . . . . . . . . . . 624
14.4 Debug Android Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
14.5 Dark Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
14.6 Kotlin Class: Conversion Between Java and Kotlin Code . . . . . 636
14.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 640
15 Real Project Practice: Creating a Weather App . . . . . . . . . . . . . . . 641
15.1 Analysis Before Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
15.2 Git Time: Host Code on GitHub . . . . . . . . . . . . . . . . . . . . . . . 645
15.3 Introduction to MVVM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651
15.4 Search City Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655
15.4.1 Business Logic Implementation . . . . . . . . . . . . . . . . . 656
15.4.2 UI Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . 661
15.5 Display Weather Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
15.5.1 Business Logic Implement . . . . . . . . . . . . . . . . . . . . 668
15.5.2 Implement UI Layer . . . . . . . . . . . . . . . . . . . . . . . . . 674
15.5.3 Record City Selection . . . . . . . . . . . . . . . . . . . . . . . . 685
15.6 Manual Refresh and Switch City . . . . . . . . . . . . . . . . . . . . . . 688
15.6.1 Manual Refreshing Weather . . . . . . . . . . . . . . . . . . . 688
15.6.2 Switching Cities . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690
15.7 Create App Icon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695
15.8 Generate Signed APK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700
15.8.1 Generating with Android Studio . . . . . . . . . . . . . . . . 701
15.8.2 Generating with Gradle . . . . . . . . . . . . . . . . . . . . . . . 702
15.9 More To Do . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
Chapter 1
Your First Line of Android Code

Welcome to the Android World! Android is by now the most popular mobile
operating system (OS) in the world, and you can find Android phones wherever
you go. But do you know how did Android has become the world’s
No. 1 mobile OS? Let us take a look at the history of Android.
In October 2003, Andy Rubin and a few others founded the Android Inc. In
August 2005, Google acquired Android Inc. which was only 22 months old at that
time. Andy Rubin stayed and continued to be responsible for the Android project.
After years of R&D, Google released the first version of Android OS in 2008.
However, ever since then Android has faced lots of backlashes. Steve Jobs insisted
that Android was an iOS knockoff that stole the ideas of iOS, and he threatened to
destroy Android at all costs. Android OS is based on Linux, but it was removed from
the Linux kernel main branch by Linux team in 2010. Since all the apps in Android
were developed with Java in the early days, Oracle also sued Google for intelligence
infringement. . .
However, all of these couldn’t stop Android from taking up the market share
rapidly. Google made Android an open OS which means that any OEM or person
can get the source code of Android OS for free, and can use and customize the OS
freely. Samsung, HTC, Motorola, Sony-Ericsson, etc., all released their Android
phones. After being released for 2 years, Android had already overtaken Nokia
Symbian which had been the leader of the smartphone mobile OS market for more
than 10 years. At that time, millions of new Android devices were activated every
day. Today, Android has more than 70% of global smartphone OS market share.
Now you must feel so excited and are eager to be an Android developer. Just
think that about 7 out of every 10 individuals’ phone can run the app you write. Is
there anything else that can be more exciting than this? Now, let’s start the journey of
learning Android development, and I will guide you how to be an excellent Android
developer step by step.

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2022 1
L. Guo, The First Line of Code, https://doi.org/10.1007/978-981-19-1800-1_1
2 1 Your First Line of Android Code

1.1 Android: An Overview

More than 20 versions of Android have been released so far, and Google has built a
holistic ecosystem during the past years. OEMs, developers, and users all play an
important role in this ecosystem, and they work together to push the evolution of
Android. Developers make a crucial part of this ecosystem, since no matter how
good the OS is, if there are not enough apps available, users wouldn’t feel like using
the OS. Who will use an OS that does not support Facebook, Messenger, or
Instagram? Furthermore, Google Play is the marketplace for Android apps, and if
you can make high-quality apps that can attract users, then you can get good return
from your apps. If your app is popular, you can even become an independent
developer to support yourself or even create a startup!
Now let’s take a look at the Android OS through the lens of an Android
developer. It can be very boring to focus on the theoretical topics. Thus, I will
cover only the important topics that you will use for developing Android apps.

1.1.1 Android System Architecture

Let’s take a look at the system architecture to understand how Android OS works.
Roughly, Android can be divided into four layers: Linux kernel layer, system lib
layer, application framework layer, and the applications layer.
1. Linux Kernel Layer
Android is based on Linux kernel, and this layer provides the drivers for the
various hardware of Android devices, for example, display driver, audio driver,
camera driver, blue-tooth driver, Wi-Fi driver, battery management, etc.
2. System Libraries Layer
This layer provides primal support to the system with some C/C++ libraries.
For example, SQLite provides database support for the database, OpenGL/ES
provides support for 3D graphics, Webkit lib provides support for browser
kernel, etc.
Android runtime is also in this layer, which provides some core libraries to
allow developers to develop Android apps with Java. The Dalvik virtual machine
is also in the runtime (replaced with ART after version 5.0), and it allows the apps
to run in their own processes and have their own virtual machine instances.
Compared with Java virtual machine (JVM), Dalvik and ART have been specif-
ically optimized for mobile devices which usually have less memory and com-
puting power.
3. Application Framework Layer
This layer provides all kinds of APIs that developers use to build the apps. The
Android system apps utilize these APIs.
1.1 Android: An Overview 3

Fig. 1.1 Android system architecture. (Source: Clipped from official documentary page)

4. Applications Layer
All the apps are belonging to this layer, for example, system apps like Contact,
Message, and the apps you downloaded from Google Play, and of course the apps
you’re going to build.
See Fig. 1.1 to get have a better understanding of the system architecture of
Android.

1.1.2 Released Versions

In September 2008, Google released the first version of Android—Android 1.0. In


the following years, Google kept updating Android at an amazing speed. v2.1, v2.2,
and v2.3 helped Android to grab a huge market share. In February 2011, Google
released Android 3.0, which was dedicated to tablet and was one of the few versions
that didn’t get traction. Soon, in October of the same year, Google released Android
4.0 which stopped treating phone and tablet differently and could be used in both
phone and tablet. In 2014, Google released Android 5.0 which claimed to have the
4 1 Your First Line of Android Code

Table 1.1 List of different versions of Android


Version number Codename API Market share
2.3.3–2.3.7 Gingerbread 10 0.3%
4.0.3–4.0.4 Ice Cream Sandwich 15 0.3%
4.1.x Jelly Bean 16 1.2%
4.2.x 17 1.5%
4.3 18 0.5%
4.4 KitKat 19 6.9%
5.0 Lollipop 21 3%
5.1 22 11.5%
6.0 Marshmallow 23 16.9%
7.0 Nougat 24 11.4%
7.1 25 7.8%
8.0 Oreo 26 12.9%
8.1 27 15.4%
9 Pie 28 10.4%

most drastic changes in the history of Android. That version used ART to replace
Dalvik virtual machine which greatly boosted the speed of apps. The concept of
Material Design also came from that version to help optimize the UI design. Google
also released OS that can be used in specific devices such as Android wear, Android
Auto, and Android TV at the same time. After that, Google accelerated the speed of
releasing Android OS updates and would release a new version every year. By 2019,
Android was already at v10.0 which was also the latest version when I wrote this
book. Check https://developer.android.com/about/versions for the newest updates.
Combine this with Fig. 1.1 to get a better understanding (Table 1.1).
From Table 1.1, we can see that v5.0 and above already have more than 85% of
Android market and this number is only going to increase, thus the apps we build
will only target v5.0 and above.

1.1.3 What’s Special for Android Development?

Let us first look at what does Android system provide for us to develop quality apps.
1. Four Main Components
The four main components of Android application development are Activity,
Service, BroadcastReceiver, and ContentProvider. Activity is used to display the
UI of the app, and everything you can see are hosted in Activity. Unlike Activity,
Service is invisible, instead, it can run in the background even if the user exits the
app. BroadcastReceiver allows your app to receive the broadcast messages from
apps like Phone and Message. Of course, your app can also send broadcast
messages. ContentProvider can be used to share data between different apps.
1.2 Set Up Development Environment Step by Step 5

For example, you need the help of ContentProvider to read the contacts in the
system Contact app.
2. Rich System Widgets
Android provides plenty of system widgets to help developers build beautiful
UIs. Of course, you can always create your own widgets to meet your special
requirement.
3. SQLite Database
Android is embedded with SQLite database, which is a lightweight and
superfast relational database. It supports standard SQL syntax and can be
accessed using APIs provided by the system which make CRUD operations
super-easy.
4. Powerful Multimedia Support
Android provides very powerful multimedia support like music, videos, voice
recording, taking photos, etc. You can use the supported APIs to make
miscellaneous apps.
With all the things Android has to offer, there is really no need to worry that
you can’t build the app you want in Android.

1.2 Set Up Development Environment Step by Step

An old saying goes like this—to do a good job, an artisan needs the best tools. It’s
not a good idea to use notepad to build Android apps. Instead, a powerful IDE can
boost your productivity dramatically. So, let us see how to set up the environment
step by step.

1.2.1 Prerequisite Tools

You need the following to build Android apps.


• JDK. JDK is the Java language development kit which contains the Java runtime,
basic libraries, etc.
• Android SDK. Android SDK is the Android development kit provided by
Google; we need to use the APIs in the SDK to build Android app.
• Android Studio. Eclipse used to be the most popular IDE to develop Android
apps which every Java developer should be very familiar with. To develop
Android app in Eclipse, you just need to install the ADT plugin. However, in
2013, Google released Android Studio. It is not a plugin but a real IDE with a
suite of tools to help you and it’s way more powerful than Eclipse. Thus, we will
use Android Studio exclusively in this book.
6 1 Your First Line of Android Code

Fig. 1.2 Select “Do not


import settings”

1.2.2 Set Up the Environment

You don’t need to download those tools one by one since Google already put
everything together into a package. Go to the official website at https://developer.
android.google.cn/studio to download the tools.
After downloading the installer, you can just click “Next” all the way to finish the
process.
After installation, when you first open the IDE, Android Studio will ask to import
the previous settings. It is not needed since it’s our first time to install it, thus select
“Do not import settings,” as shown in Fig. 1.2.
Click “OK” to go to the wizard screen as shown in Fig. 1.3.
Click “Next” to start configuration as shown in Fig. 1.4.
Here, you can choose from “Standard” and “Custom.” The “Standard” option will
use the default configuration which is more convenient, and we will just use
“Standard” for now. Click “Next” to go to the screen to select UI theme, as shown
in Fig. 1.5.
There are two initial themes for you to choose from and I will just use the default
“Light theme” here, click “Next” to finish the configuration as shown in Fig. 1.6.
Now click “Finish” to finish all the configuration steps. After this, Android Studio
will try to connect to the network and then download some updates. After updates
are done, click “Finish” should open the Android Studio welcome screen as shown
in Fig. 1.7.
Now that the development environment has been set up, let us write our first line
of Android code!

1.3 Creating Your First Android Project

By convention, we should write the Hello World program as our first program, and
we will respect this convention in this book.
1.3 Creating Your First Android Project 7

Fig. 1.3 Android Studio configuration screen

1.3.1 Creating HelloWorld Project

In the Android Studio welcome screen, click Start a new Android Studio project
should open a screen to allow you to select project type as shown in Fig. 1.8.
From this screen, we can select project type for phones, tablets, wearable devices,
TVs, and even for cars. We will focus on phone and tablet in this book. Android
Studio also provides lots of templates which we won’t use for now since most of the
templates are too complicated for starters and we will start with Empty Activity.
Click “Next” to go to the project configuration screen as shown in Fig. 1.9.
Use HelloWorld for the project Name.
Package name is the name that Android uses to distinguish between different
apps, thus we need to make this name unique. Android Studio will help us generate a
proper package name based on our app’s name and you can change it as you wish.
Save location is where the project will be, and I will use the default selection here.
Language option is important and here it chooses Kotlin by default. Java used to
be the language exclusively used to develop Android apps. In 2017, Google intro-
duced Kotlin to the Android land and announced that Kotlin should be the first
choice for developers in 2019. Thus, I decided to use Kotlin to write all the code in
this book in V3. Don’t worry if you don’t know anything about Kotlin. I will cover
Kotlin extensively in this book besides Android.
8 1 Your First Line of Android Code

Fig. 1.4 Select Install Type

Minimum API level is the earliest version of Android that this project is compat-
ible with. As mentioned earlier that Android 5.0 and above already take more than
85% of the Android market share, we will set the Minimum SDK to be API 21.
The instant run option allows the app code can be pushed dynamically and is
outside the scope of this book. AndroidX is in the process of replacing the old
Android Support Library and in Android Studio 3.5.2, this option has been selected
by default. In later versions of Android Studio this option may be gone since all
projects will have to use AndroidX.
Now click “Finish” and the project should successfully get created in a moment as
shown in Fig. 1.10.

1.3.2 Starting Emulator

You don’t need to write any code to be able to run this app because Android Studio
already generated everything we need to run the app. But before that, we need
something that can load our app which can be an Android phone or emulator. Let’s
use an emulator for now and if you want to install and run the app in your phone,
please refer to Sect. 9.1.
1.3 Creating Your First Android Project 9

Fig. 1.5 Select UI Theme

Now let us create an Android emulator. You should find the icons at the top of the
toolbar in Android Studio as shown in Fig. 1.11.
The middle button is used to create and start the emulator. Click this button
should show a screen like shown in Fig. 1.12.
You should see an empty emulator list and click “Create Virtual Device” to start
the creation process as shown in Fig. 1.13.
There are lots of devices we can choose from like phones, tablets, watches, etc.
Here let us use Pixel which is my personal favorite. Click “Next” as shown in
Fig. 1.14.
Apparently, we want to download the latest Android OS which will require
downloading the image first. Click “Download” and after downloading finishes,
click “Next” will show a window as shown in Fig. 1.15.
Here we can verify lots of configurations like name of emulator, screen resolu-
tion, etc. If there is no special requirement, we can use the default configuration.
Click “Finish” and a window, as shown in Fig. 1.16, will show up.
Now we can see the emulator item in the emulator list and clicking the triangle
icon in Actions will start the emulator. Emulator will have a booting process like real
phones, and after that it should have a window as shown in Fig. 1.17.
Android emulators can largely emulate the real phones and you should be able to
use emulator almost like using a real phone. Try it out yourself!
10 1 Your First Line of Android Code

Fig. 1.6 Finish Configuration of Android Studio

1.3.3 Running HelloWorld

Now let’s install and run the HelloWorld project in the emulator. At the top of the
toolbar, you should see the buttons as shown in Fig. 1.18. Among them, the hammer
button is used to compile the project. The first dropdown list is used to select
the project to run and the second is for selecting the device which already shows
the emulator we just created. The right-most triangle-shaped button is for running the
app.
Now click the triangle button and wait for a few seconds until HelloWorld gets
installed and run which should be like Fig. 1.19.
You will find that HelloWorld app has been installed and you can find it from the
launcher as shown in Fig. 1.20.
Wait a second! We haven’t even written a single line of code and Hello World
already showed up! Where is our first line of Android code? Well, Android Studio
already generated the code for us, and now let us use this project to understand
Android project structure.
1.3 Creating Your First Android Project 11

Fig. 1.7 Welcome screen of Android Studio

1.3.4 Analyzing Your First Android Project

Now in Android Studio, you should be able to see the project structure as shown in
Fig. 1.21.
A newly created project will by default use the Android mode for project structure
which is not how the project is organized in the disk. This mode has a very clear
structure which can help development, but does not help for starters to understand
and navigate around. In the dropdown list (Fig. 1.21), choose Project mode
(Fig. 1.22) as shown in Fig. 1.23.
An Android project has lots of folders and files inside and you might feel
confused about what they are. Now let me explain them one by one to help you
understand the project structure.
1. .gradle and .idea
Under these two folders are some auto-generated files and we can ignore
them for now and don’t need to manually edit them.
2. app
All the code files, resource files are under this folder and apparently our work
will mostly be in this folder, and we will expand it to cover more details later.
3. build
12 1 Your First Line of Android Code

Fig. 1.8 Select Project Type Screen

This folder mainly contains the files generated during the compilation pro-
cess and again you can ignore for now.
4. gradle
This folder has the gradle wrapper config file. Using gradle wrapper can
avoid downloading gradle when not necessary. By default, Android Studio will
use gradle wrapper and if you want to use offline mode, click File- > Settings-
> Build, Execution, Deployment- > Gradle.
5. .gitignore
This file is used to allow version control tool to ignore files which means the
changes that applied to these files won’t be tracked. We will learn more about
this in Chap. 6.
6. build.gradle
This is the global build script which usually doesn’t need to be edited and we
will cover the gradle script in detail later.
7. gradle.properties
This is the config file for global gradle file which means the properties in this
file will affect all the gradle scripts in this project.
8. gradlew and gradlew.bat
1.3 Creating Your First Android Project 13

Fig. 1.9 Project Configuration Screen

Fig. 1.10 Project created successfully


14 1 Your First Line of Android Code

Fig. 1.11 Icons at the top


toolbar

Fig. 1.12 Create emulator wizard

These two files are used to execute the gradle command in CLI. gradlew is for
Linux and Mac OS. gradle.bat is for Windows.
9. HelloWorld.iml
All the IntelliJ IDEA projects will generate an iml file and since Android
Studio is based on IntelliJ IDEA thus there is an iml file in the project which we
can ignore.
10. local.properties
This file specifies the path of Android SDK in this machine and usually is
auto generated, thus we can ignore it. If the path of Android SDK in your
machine somehow gets changed, you can change to the newest path in this file.
11. settings.gradle
This is used to specify all the imported modules. Since there is only one app
module, we can only see the app here. Usually, importing modules is automat-
ically done and we don’t need to edit this file.
1.3 Creating Your First Android Project 15

Fig. 1.13 Select the device

Fig. 1.14 Select the OS version of emulator


16 1 Your First Line of Android Code

Fig. 1.15 Verify Emulator Configuration

Fig. 1.16 Emulator list

That’s everything about the outer layer structure. Most of the directories and files
except app directory are generated and we don’t need to edit them. Let us expand the
app directory which should look like Fig. 1.24.
1.3 Creating Your First Android Project 17

Fig. 1.17 Emulator Screen

Fig. 1.18 Buttons in the top toolbar

Next, let us take a deep dive into app directory.


1. build
This folder is like the outer layer build folder and contains generated files
during compilation although much more complex. Ignore for now.
2. libs
You should put the third-party jar package in this folder which will be
automatically added to the build path of this project.
3. androidTest
The automated test code should reside in this directory.
4. java
18 1 Your First Line of Android Code

Fig. 1.19 Run the


HelloWorld project

Obviously, this is the directory that all of our Java (Kotlin) code will
be. Expand the folder, you should see MainActivity file which is generated by
the IDE.
5. res
There will be lots of things under this directory. Basically, all the resources
you use for the project like images, layouts, strings, etc. should all be put under
this directory. In order to keep them organized, they should be put into their
corresponding folders like drawable folder for images, layout folder for
layouts, etc.
6. AndroidManifest.xml
This is the config file for the whole Android project and all the four compo-
nents you use in the project need to register in this file. You can add authority to
the app in this file. This is a commonly used file and we will discuss this when
we need to.
7. test
1.3 Creating Your First Android Project 19

Fig. 1.20 Launcher

Fig. 1.21 Project structure


in Android mode
20 1 Your First Line of Android Code

Fig. 1.22 Switching


Project Structure Mode

Fig. 1.23 Project Model


Structure

This folder is used for unit test files.


8. .gitignore
This file will allow the version control program to ignore files in app
directory which is similar to the outer layer .gitignore file.
9. app.iml
Another IntelliJ IDEA generated file and we don’t need to care.
10. build.gradle
This is the app module’s gradle build script which will specify lots of
configurations for building the project, we will cover the contents in the script
shortly.
1.3 Creating Your First Android Project 21

Fig. 1.24 File structure


under app

11. proguard-rules.pro
This is used for specifying the rules for code obfuscation. Obfuscation is used
when you don’t want your source code to be seen by other people.
That’s all for the structure of the project. You might still have difficulty under-
standing everything mentioned here and that is totally normal. After you finish the
whole book and look back, you will find the content here crystal clear and simple.
Now let us see what happens when HelloWorld starts running. First, open the
AndroidManifest.xml file and you should find the code below:

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Here, it registers MainActivity which is required so that an activity can be used.


The two lines of code between intent-filter element are very important.
<action android:name¼ "android.intent.action.Main"/> and <category android:
name¼"android.intent.category.LAUNCHER"/> means that MainActivity is the
main activity of this app and when user clicks the app icon in the phone, this activity
will be started first.
What is the role of MainActivity? In the section that covers Android four main
components, I mentioned that everything you can see in the app is hosted in the
activity. Thus, what you see in Fig. 1.19 is MainActivity. Let’s take look at its
implementation. Open the file and code should be as shown below:

class MainActivity : AppCompatActivity() {


22 1 Your First Line of Android Code

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}

First, we can see that MainActivity inherits AppCompatActivity.


AppCompatActivity is a backward compatible activity provided in AndroidX and
can ensure the same functionality in different versions of OS. Activity class is a base
class provided by Android system and every activity defined in our app must inherit
from it or its subclass to be able to inherit the functions and properties of activity.
AppCompatActivity, for example, is a subclass of activity. The onCreate() method
will be called when an activity is being created. But we cannot see “Hello World” at
all. Where is this string?
We cannot find it in the activity because it is recommended to separate business
logic and views in Android development. A widely adopted pattern is to write the UI
in the layout file and then use the layout in the activity. We can see that
setContentView() method gets called in onCreate() and it is this method that
imported the activity_main layout for the current activity. So “Hello World” must
be in this file! Let’s open it and take a look.
As mentioned before, layout files are all under res/layout folder, so you should be
able to find activity_main.xml there. Open the file and switch to Text mode, code
should be like follows:

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Feeling confused? That’s OK. I will cover more about layout in later chapters and
now you just need to focus on TextView which is a widget provided by Android
system that can show text in the layout. And you should see “Hello World!” there.
Aha, so it is actually done by android:text ¼ “Hello World!”.
Now that we’ve already learned the structure of HelloWorld project and the
mechanism of how app runs, let’s take a look at the resources in a project.
1.3 Creating Your First Android Project 23

1.3.5 Resources in a Project

Expand the res folder, you should find lots of folders and files in it as shown in
Fig. 1.25.
It might be daunting at first glance, but they are actually well organized and easy
to understand. All the folders start with “drawable” are used for images; “mipmap”
directories are used for app icons; “values” directories are for strings, colors, etc.;
and “layout” directories are used for layouts. Now the directories look simple and
clear, right?
There are quite a few directories with prefix “mipmap” and “drawable.” This can
help our app use different resources when run on different devices. Android Studio
won’t generate the drawable-hdpi, drawable-xhdpi, drawable-xxhdpi folders and we
need to create them by ourselves. When we develop an app, it’s recommended that
we get different resolutions of the same image and put them into corresponding
folders. Then the right resolution resource will be selected based on the resolution of
current device. Of course, this is the ideal case most of the time—we might just get
one picture, then we can put the images in drawable-xxhdpi since this is the most
popular devices’ resolution.
Now let us look at how to use these resources. Open res/value/strings.xml file,
and you should see code as follows:

<resources>
<string name="app_name">HelloWorld</string>
</resources>

Here, a string of the app’s name gets defined and we have two ways to use it.

Fig. 1.25 Folders under res


24 1 Your First Line of Android Code

• Use R.string.app_name in Kotlin, Java code to get the reference of this string.
• Use @string/app_name in XML file.
These are the two most common ways of getting reference of resources; we can
replace string here with drawable to get image, with mipmap to get the icon, and
so on.
Let us use an example to help understanding. Open AndroidManifest.xml file and
find the code as shown below:

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
...
</application>

Here, android:icon attribute specifies the HelloWorld app icon, android:label


attribute specifies the name of the app. You can see the way to get these resources
is exactly as we just mentioned.
Now you should know how to change the app icon or name of the app, right?

1.3.6 File of build.gradle

Unlike Eclipse, Android Studio uses Gradle to build the project. Gradle is an
advanced tool to build the project which uses a DSL (Domain Specific Language)
based on Groovy to configure the project and avoids the complicated configuration
with XML-based tools like Ant and Maven.
From Sect. 1.3.4, we can see that there are two build.gradle files in HelloWorld
project. One is at the outer layer and another one is under the app directory. These
two files are instrumental to build the Android Studio projects and let us take a deep
dive into these two files.
First look at the build.gradle file at the outer layer as shown below:

buildscript {
ext.kotlin_version = '1.3.61'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$
kotlin_version"
1.3 Creating Your First Android Project 25

}
}

allprojects {
repositories {
google()
jcenter()
}
}

Code here is generated and its syntax may look confusing. However, if we ignore
the syntax and focus on some key parts, it should be easy to understand.
First, the two repository closures all use google() and jcenter() methods. These
two methods are used to specify the code repository that this project is going to use.
The google repo is Google’s Maven repo and jcenter is the repo mainly for third-
party open sources libs. With these two methods, we can easily use any libs in the
google and jcenter repo.
Next, in the dependencies closure, classpath specifies Gradle plugin and Kotlin
plugin. Why need to specify Gradle plugin? This is because Gradle wasn’t specif-
ically created for building Android projects but for other types of projects written in
Java, C++, etc. If we want to use it to build the Android project, we need to specify in
Gradle to use com.android.tools.build:gradle:3.5.2 plugin. The series number at the
end is the plugin version number and should be the same as the current Android
Studio version number. The Kotlin plugin just means that the current project is
written with Kotlin. If you use Java to develop Android project, then there is no need
to use this plugin. When I wrote this book the latest version of Kotlin plugin was
1.3.61.
That’s everything for the outer layer build.gradle. Usually, you don’t need to
modify this file unless you want to make some global configuration changes.
Next, let us look at the build.gradle under the app directory, code should be the
same as follows:

apply plugin: 'com.android.application'


apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.helloworld"
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.
AndroidJUnitRunner"
}
26 1 Your First Line of Android Code

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-
optimize.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$
kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.1.0'
implementation 'androidx.constraintlayout:
constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-
core:3.2.0'
}

This file is more complicated and let us go over them line by line. The first line
applies a plugin which has two values to choose from: com.android.application
means this is an application module; com.android.library means this is a lib module.
The biggest difference between them is that the application module can run inde-
pendently while lib module will need to be loaded in other apps so that it can run.
The next two lines apply the kotlin-android plugin and kotlin-android-extensions
plugin. If you want to use Kotlin to develop Android app, then you must add the first
plugin. The second plugin provides some useful extensions of Kotlin which you will
find out in later chapters.
Next is a large android closure in which we can configure everything needed to
build the project. Among them, compileSdkVersion is used to specify the SDK
version used to compile the project and here we set it to SDK 29 which is Android
V10.0. If there is a newer version, Android Studio will notify you.
Then we can see a defaultConfig closure within the Android closure which can
specify more details about the project configuration. In this closure, applicationId is
the unique identifier of the app and cannot be duplicated. By default, it will use the
package name we specified when we created the project. minSdkVersion is used to
specify the oldest version of Android that this project is compatible with, and we set
it to 21 which is Android 5.0. targetSdkVersion specifies the target Sdk version
which means that you’ve already extensively tested the app in this version and the
system can open some new functionality or features to the app. For example, runtime
permissions were introduced in Android 6.0. If you specify the targetSdkVersion to
be 23 or higher, then the system will allow the app to use runtime permissions.
However, if you specify targetSdkVersion to 22, then this means that you only have
done extensive testing in Android 5.1 and lower versions, thus runtime permissions
Discovering Diverse Content Through
Random Scribd Documents
to imagine himself melted into one and united with him, and,
indeed, to have become the same person.
This decidedly literal faith had also worked in him a perfect
conviction that miracles can be wrought to-day as well as heretofore.
Accordingly, since in some important and trying emergencies of his
earlier days, he had by means of earnest and indeed violent prayer,
succeeded in procuring an instantaneous and favorable turn of the
impending calamity, no mere cold objections of the reasoning
intellect would make him for a moment waver in this faith.
Penetrated, moreover, by the idea of the greatness and excellence of
Humanity as restored by Christ, and through Him destined to a
blissful immortality, but, at the same time, fully sensible of the
manifold requisitions of man's heart and mind, and of his insatiable
yearnings after knowledge, and, moreover, feeling in himself that
desire of expanding himself into the infinite to which the starry
heavens seem so sensibly to invite us, he wrote under these feelings
Iris "Prospects of Eternity," which must have appeared a very
strange book indeed to the greater part of his contemporaries.
All this striving, however, all wishes, all undertakings, were
overborne by the genius for physiognomy, which nature had
bestowed upon him. For, as the touchstone, by its blackness and
peculiar roughness of surface, is eminently fitted to distinguish
between the metals which are applied to it; so that pure idea of
humanity, which Lavater carried within himself, and that sharp yet
delicate gift of observation, which at first he exercised from natural
impulse occasionally only and accidentally, but afterwards with
deliberate reflection and regularly, qualified him in the highest
degree to note the peculiarities of individual men, and to
understand, distinguish, and express them.
Every talent which rests on a decided natural gift, seems from our
inability to subordinate either it or its operations to any idea to have
something of magic about it. And, in truth, Lavater's insight into the
characters of individuals surpassed all conception; one was utterly
amazed at his remarks, when in confidence we were talking of this
or that person; nay, it was frightful to live near a man who clearly
discerned the nicest limits by which nature had been pleased to
modify and distinguish our various personalities.
Every one is apt to believe that what he possesses himself may be
communicated to others; and so Lavater was not content to make
use of this great gift for himself alone, but insisted that it might be
found and called forth in others, nay that it might even be imparted
to the great mass. The many dull and malicious misinterpretations,
the stupid jests in abundance, and detracting railleries, this striking
doctrine gave rise to, may still be remembered by some men;
however, it must be owned that the worthy man himself was not
altogether without blame in the matter. For though a high moral
sense preserved the unity of his inner being, yet, with his manifold
labors, he was unable to attain to outward unity, since he did not
possess the slightest capacity for philosophical method, nor for
artistic talent.
He was neither Thinker nor Poet; indeed, not even an orator, in the
proper sense of the term. Utterly unable to take a comprehensive
and methodical view, he nevertheless formed an unerring judgment
of individual cases and these he noted down boldly side by side. His
great work on Physiognomy is a striking proof and illustration of this.
In himself, the idea of the moral or of the sensual man might form a
whole; but out of himself he could not represent this idea, except
practically by individual cases, in the same way as he himself had
apprehended them in life.
That very work sadly shows us how in the commonest matter of
experience so sharp-sighted a man, may go groping about him. For
after spending an immense sum and employing every artist and
botcher living, he procured at last drawings and engravings, which
were so far without character, that he is obliged in his work to say
after each one that it is more or less a failure, unmeaning and
worthless. True, by this means, he sharpened his own judgment,
and the judgment of others; but it also proves that his mental bias
led him rather to heap up cases of experience, than to draw from
them any clear and sober principle. For this reason he never could
come to results, though I often pressed him for them. What in later
life he confided as such to his friends, were none to me; for they
consisted of nothing more than a collection of certain lines and
features, nay, warts and freckles, with which he had seen certain
moral, and frequently immoral, peculiarities associated. There were
certainly some remarks among them that surprised and riveted your
attention; but they formed no series, one thing followed another
accidentally, there was no gradual advance towards any general
deductions and no reference to any principles previously established.
And indeed there was just as little of literary method or artistic
feeling to be found in his other writings, which invariably contained
passionate and earnest expositions of his thoughts and objects, and
supplied by the most affecting and appropriate instances, what they
could not accomplish by the general conception.

The following reflections, as they refer to those


circumstances, may be aptly introduced here. Abuse of the Term
—Genius.
No one willingly concedes superiority to another, so
long as he can in any way deny it. Natural gifts of every kind can the
least be denied, and yet by the common mode of speaking in those
times, genius was ascribed to the poet alone. But another world
seemed all at once to rise up; genius was looked for in the
physician, in the general, in the statesman, and before long, in all
men, who thought to make themselves eminent either in theory or
practice. Zimmerman, especially, had advanced these claims.
Lavater, by his views of Physiognomy, was compelled to assume a
more general distribution of mental gifts by nature; the word genius
became a universal symbol, and because men heard it uttered so
often, they thought that what was meant by it, was habitually at
hand. But then, since every one felt himself justified in demanding
genius of others, he finally believed that he also must possess it
himself. The time was yet far distant when it could be affirmed, that
genius is that power of man which by its deeds and actions gives
laws and rules. At this time it was thought to manifest itself only, by
overstepping existing laws, breaking established rules, and declaring
itself above all restraint. It was, therefore, an easy thing to be a
genius, and nothing was more natural than that extravagance both
of word and deed should provoke all orderly men to oppose
themselves to such a monster.
When anybody rushed into the world on foot, without exactly
knowing why or whither, it was called a pass of genius; and when
any one undertook an aimless and useless absurdity, it was a stroke
of genius. Young men, of vivacious and true talents, too often lost
themselves in the limitless; and then older men of understanding,
wanting perhaps in talent and in soul, found a most malicious
gratification in exposing to the public gaze, their manifold and
ludicrous miscarriages.
For my part, in the development and the expression of my own
ideas, I perhaps experienced far more hindrance and checks from
the false co-operation and interference of the like-minded, than by
the opposition of those whose turn of mind was directly contrary to
my own.
With a strange rapidity, words, epithets, and phrases, which have
once been cleverly employed to disparage the highest intellectual
gifts, spread by a sort of mechanical repetition among the multitude,
and in a short time they are to be heard everywhere, even in
common life, and in the mouths of the most uneducated; indeed
before long they even creep into dictionaries. In this way the word
genius had suffered so much from misrepresentation, that it was
almost desired to banish it entirely from the German language.
And so the Germans, with whom the common voice is more apt to
prevail than with other nations, would perhaps have sacrificed the
fairest flower of speech, the word which, though apparently foreign,
really belongs to every people, had not the sense for what is highest
and best in man, been happily restored and solidly established by a
profounder philosophy.
In the preceding pages mention has been frequently made of the
youthful times of two men, whose memory will never hide from the
history of German literature and morals. At this period, however, we
came to know them as it were only by the errors into which they
were misled by a false maxim which prevailed among their youthful
contemporaries. Nothing, therefore, can be more proper than with
due appreciation and respect to paint their natural form, their
peculiar individuality, just as it appeared at that time, and as their
immediate presence exhibited itself to the penetrating eye of
Lavater. Consequently, since the heavy and expensive volumes of the
great work on Physiognomy are probably accessible to a few only of
our readers, I have no scruple in inserting here the remarkable
passages of that work, which refer to both the Stolbergs, in the
second part and its thirtieth fragment, page 224:
"The young men, whose portraits and profiles we
have here before us, are the first men who ever sat Lavater's Sketch
of the Stolbergs.
and stood to me for physiognomical description, as
another would sit to a painter for his portrait.
"I knew them before, the noble ones—and I made the first attempt,
in accordance with nature and with all my previous knowledge, to
observe and to describe their character.
"Here is the description of the whole man.—

FIRST, OF THE YOUNGER.


"See the blooming youth of 25! the lightly-floating, buoyant, elastic
creature! it does not lie; it does not stand; it does not lean; it does
not fly; it floats or swims. Too full of life, to rest; too supple to stand
firm; too heavy and too weak, to fly.
"A floating thing, then, which does not touch the earth! In its whole
contour not a single slack line; but on the other hand no straight
one, no tense one, none firmly arched or stiffly curved; no sharp
entering angles, no rock-like projection of the brow; no hardness; no
stiffness; no defiant roughness; no threatening insolence; no iron
will—all is elastic, winning, but nothing iron; no stedfast and
searching profundity; no slow reflection, or prudent thoughtfulness;
nowhere the reasoner with the scales held firmly in the one hand,
and the sword in the other; and yet not the least formality in look or
judgment! but still the most perfect straight-forwardness of intellect,
or rather the most immaculate sentiment of truth! Always the inward
feeler, never the deep thinker; never the discoverer, the testing
unfolder of truth so quickly seen, so quickly known, so quickly loved,
and quickly grasped.... Perpetual soarer, a seer; idealizer; beautifier;
—that gives a shape and form, to all his ideas! Ever the half-
intoxicated poet, seeing only what he will see;—not the sorrowfully
languishing; not the sternly crushing; but the lofty, noble, powerful!
who with 'thirst for the sun' (Sonnendurst), hovers to and fro in the
regions of air, strives aloft, and again—sinks not to earth! but throws
himself headlong to earth, bather in the floods of the 'Rock-stream'
(Felsenstrom), and cradles himself 'in the thunder of the echoing
rocks around' (Im Donner der hallenden Felsen umher). His glance—
not the fire-glance of the eagle! His brow and nose—not the courage
of the lion! his breast—not the stedfastness of the steed that neighs
for battle! In the whole, however, there is much of the tearing
activity of the elephant....
"The projecting upper lip slightly drawn up towards the over-hanging
nose, which is neither sharply cut, nor angular, evinces, with such a
closing of the mouth, much taste and sensibility; while the lower
part of the face bespeaks much sensuality, indolence, and
thoughtlessness. The whole outline of the profile shows openness,
honesty, humanity, but at the same tune a liability to be led astray,
and a high degree of that good-hearted indiscretion, which injures
no one but himself. The middle line of the mouth bespeaks in its
repose, a downright, planless, weak, good-natured disposition; when
in motion, a tender, finely-feeling, exceedingly susceptible,
benevolent, noble man. In the arch of the eyelids, and in the glance
of the eyes, there sits not Homer, but the deepest, most thorough,
and most quick feeling, and comprehension of Homer; not the epic,
but the lyric poet; genius, which fuses, moulds, creates, glorifies,
hovers, transforms all into a heroic form—which deifies all. The half-
closed eyelids, from such an arch, indicate the keenly sensitive poet,
rather than the slowly laboring artist, who creates after a plan; the
whimsical rather than the severe. The full face of the youth is much
more taking and attractive, than the somewhat too loose, too
protracted half-face; the fore-part of the face in its slightest motion,
tells of a highly sensitive, thoughtful, inventive, untaught, inward
goodness, of a softly tremulous, wrong-abhorring love of liberty—an
eager vivacity. It cannot conceal from the commonest observer the
slightest impression which it receives for the moment, or adopts for
ever. Every object, which nearly concerns or interests him, drives the
blood into the cheeks and nose; where honor is concerned, the most
maidenly blush of shame spreads like lightning over the delicately
sensitive skin.
"The complexion is not the pale one of all-creating,
all-consuming genius; not the wildly glowing one of Lavater's Sketch
of the Stolbergs.
the contemptuous destroyer; not the milk-white
one of the blond; not the olive one of the strong and hardy; not the
brownish one of the slowly plodding peasant; but the white, the red,
and the violet, running one into another, and so expressively, and so
happily, blended together like the strength and weakness of the
whole character. The soul of the whole and of each single feature is
freedom, and elastic activity, which springs forth easily and is as
easily repulsed. The whole fore-face and the way the head is carried,
promise magnanimity and upright cheerfulness. Incorruptible
sensibility, delicacy of taste, purity of mind, goodness and nobleness
of soul, active power, a feeling of strength and of weakness, shine
out so transparently through the whole face, that what were
otherwise a lively self-complacency dissolves itself into a noble
modesty, and most artlessly and unconstrainedly the natural pride
and vanity of youth melt with the loveliness of twilight into the easy
majesty of the whole man. The whitish hair, the length and
awkwardness of form, the softness and lightness of step, the
hesitating gait, the flatness of the breast, the fair unfurrowed brow,
and various other features spread over the whole man a certain
feminine air, by which the inward quickness of action is moderated,
and every intentional offence and every meanness made for ever
impossible to the heart; but at the same time clearly evincing that
the spirited and fiery poet, with all his unaffected thirst for freedom
and for emancipation, is neither destined to be a man of business,
thoroughly persistent, who steadily and resolutely carries out his
plans, or to become immortal in the bloody strife. And now, in
conclusion, I remark, for the first time, that I have as yet said
nothing of the most striking trait—the noble simplicity, free from all
affectation! Nothing of his childlike openness of heart! Nothing of the
entire unconsciousness of his outward nobility! Nothing of the
inexpressible bonhommie with which he accepts and bears
reproaches or warnings, nay, even accusations and wrongful
charges.
"But who can find an end, who will undertake to tell all that he sees
or feels in a good man, in whom there is so much pure humanity?"

DESCRIPTION OF THE ELDER STOLBERG.


"What I have said of the younger brother—how much of it may be
said also of the elder! The principal thing I have to remark is the
following:—
"This figure and this character are more compact and less diffuse
than the former. There all was longer or flatter; here all is shorter,
broader, more arched, and rounded; there all was vague; here
everything is more precise and sharply defined. So the brow; so the
nose; so the breast: more compressed, more active, less diffuse,
more of concentrated life and power! For the rest, the same
amiableness and bonhommie! Not that striking openness, rather
more of reserve, but in principle, or rather in deed, the same
honorable tone. The same invincible abhorrence of injustice and
baseness; the same irreconcilable hatred of all that is called cunning
and trickery; the same unyielding opposition to tyranny and
despotism; the same pure, incorruptible sensibility to all that is
noble, and great, and good; the same need of friendship and of
freedom, the same sensitiveness and noble thirst for glory; the same
catholicity of heart for all good, wise, sincere, and energetic men,
renowned or unrenowned, known or misunderstood,—and the same
light-hearted inconsiderateness. No! not exactly the same. The face
is sharper, more contracted, firmer; has more inward, self-developing
capacity for business and practical counsels; more of enterprising
spirit—which is shown especially by the strongly prominent and fully
rounded bones of the eye-sockets. Not the all-blending, rich, pure,
lofty poet's feeling—not the ease and rapidity of the productive,
power which marks the other—but yet he is, and that in profounder
depths, vivacious, upright, ardent. Not the airy genius of light
floating away in the morning red of heaven, and fashioning huge
shapes therein—but more of inward power, though perhaps less of
expression! more powerful and terrible—less of elegance and finish;
though his pencil nevertheless wants neither coloring nor
enchantment. More wit and riotous humor; droll satire; brow, nose,
look—all so downward, so over-hanging—decidedly what it should be
for original and all-enlivening wit, which does not gather from
without, but brings forth from within. Above all in this character
every trait more prominent, more angular, more aggressive, more
storming! No passive dullness, no relaxation, except in the sunken
eyes, where, as well as in the brow and nose, pleasure evidently
sits. In all besides—and even in this very brow, this concentration of
all—in this look indeed—there is an unmistakable expression of
natural, unacquired greatness; strength, impetuosity of manliness;
constancy, simplicity, precision!"

After having in Darmstadt conceded to Merck the justice of his


opinions and allowed him to triumph, in his having predicted my
speedy separation from these gay companions, I found myself again
in Frankfort, well received by every one, including my father,
although the latter could not conceal his disappointment that I had
not descended by the pass to Airolo, and announced to him from
Milan my arrival in Italy. All this was expressed by his silence rather
than his words; but above all he did not show the slightest sympathy
with those wild rocks, those lakes of mist, and dragons' nests.
At last, however, by an incidental remark, by no means intended for
a reproach, he gave me to understand how little all such sights were
worth: he who has not seen Naples, he observed, has lived to no
end.
On my return I did not, I could not, avoid seeing
Lili; the position we maintained towards each other My Meeting again
with Lili.
was tender and considerate. I was informed that
they had fully convinced her in my absence, that she must break off
her intimacy with me, and that this was the more necessary and
indeed more practicable, since by my journey and voluntary
absence, I had given a sufficiently clear intimation of my own
intentions. Nevertheless, the same localities in town and country, the
same friends, confidentially acquainted with all the past, could
scarcely be seen without emotion by either of us—still and for ever
lovers, although drawn apart in a mysterious way. It was an
accursed state, which in a certain sense resembled Hades, or the
meeting of the happy with the unhappy dead.
There were moments when departed days seemed to revive, but
instantly vanished again, like ghosts.
Some kind people had told me in confidence, that Lili, when all the
obstacles to, our union were laid before her, had declared that for
my love she was ready to renounce all present ties and advantages,
and to go with me to America. America was then perhaps, still more
than now, the Eldorado of all who found themselves crossed in the
wishes of the moment.
But the very thing which should have animated my hopes, only
depressed them the more. My handsome paternal house, only a few
hundred steps from hers, offered certainly a more tolerable and
more attractive habitation than an uncertain and remote locality
beyond the ocean; still I do not deny, that in her presence all hopes,
all wishes sprang to life again, and irresolution was stirring within
me.
True, the injunctions of my sister were very peremptory and precise;
not only had she, with all the shrewd penetration of which she was
mistress, explained the situation of things to me, but she had also,
with painfully cogent letters, harped upon the same text still more
powerfully. "It were very well," said she, "if you could not help it,
then you would have to put up with it; such things one must suffer
but not choose." Some months passed away in this most miserable
of all conditions; every circumstance had conspired against the
union; in her alone I felt, I knew, lay the power which could have
overcome every difficulty.
Both the lovers, conscious of their position, avoided all solitary
interviews; but, in company, they could not help meeting in the
usual formal way. It was now that the strongest trial was to be gone
through, as every noble and feeling soul will acknowledge, when I
have explained myself more fully.
It is generally allowed, that in a new acquaintance, in the formation
of a new attachment, the lover gladly draws a veil over the past.
Growing affection troubles itself about no antecedents, and as it
springs up like genius with the rapidity of lightning, it knows nothing
either of past or future. It is true, my closer intimacy with Lili had
begun by her telling me the story of her early youth: how, from a
child up, she had excited in many both a liking and devotion to
herself, especially in strangers visiting her father's gay and lively
house, and how she had found her pleasure in all this, though it had
been attended with no further consequences and had lead to no
permanent tie.
True, lovers consider all that they have felt before
only as preparation for their present bliss, only as Lili's Old Lovers.
the foundation on which the structure of their
future life is to be reared. Past attachments seem like spectres of the
night, which glide away before the break of day.
But what occurred! The fair came on, and with it appeared the
whole swarm of those spectres in their reality; all the mercantile
friends of the eminent house came one by one, and it was soon
manifest that not a man among them was willing or able wholly to
give up a certain claim to the lovely daughter. The younger ones,
without being obtrusive, still seemed to claim the rights of familiar
friends; the middle-aged, with a certain obliging dignity, like those
who seek to make themselves beloved, and who in all probability
might come forward with higher claims. There were fine men among
them, with the additional recommendation of a substantial fortune.
The older gentlemen, with their uncle's ways and manners, were
altogether intolerable; they could not bridle their hands, and in the
midst of their disagreeable twaddle would demand a kiss, for which
the cheek was not refused. It was so natural to her, gracefully to
satisfy every one. The conversation, too, excited many a painful
remembrance. Allusion was constantly made to pleasure parties by
water and by land, to perils of all kinds with their happy escapes, to
balls and evening promenades, to the amusement afforded by
ridiculous wooers, and to whatever could excite an uncomfortable
jealousy in the heart of an inconsolable lover, who had, as it were,
for a long time drawn to himself the sum of so many years. But amid
all this crowd and gaiety, she did not push aside her friend, and
when she turned to him, she contrived, in a few words, to express
all the tenderness which seemed allowable to their present position.
But let us turn from this torture, of which the memory even is almost
intolerable, to poesy, which afforded, at least, an intellectual and
heartfelt alleviation of my sufferings.
"Lili's Menagerie" belongs somewhere to this period; I do not adduce
the poem here, because it does not reveal the softer sentiment, but
seeks only, with genial earnestness, to exaggerate the disagreeable,
and by comical, and provoking images, to change renunciation into
despair.
The following song expresses rather the sweeter side of that misery,
and on that account is here inserted:
Sweetest roses, ye are drooping,
By my love ye were not worn;
Bloom for one, who past all hoping,
Feels his soul by sorrow torn.

Oh, the days still live in thought, love,


When to thee, my angel, bound;
I my garden early sought, love,
And for thee the young buds found.

All the flowers and fruits I bore thee,


And I cast them at thy feet;
As I proudly stood before thee,
Then my heart with hope would beat!

Sweetest roses, ye are drooping,


By my love ye were not worn;
Bloom for one, who past all hoping,
Feels his soul by sorrow torn.

The opera of "Erwin and Elvira" was suggested by the pretty little
romaunt or ballad introduced by Goldsmith in his "Vicar of
Wakefield," which had given us so much pleasure in our happiest
days, when we never dreamed that a similar fate awaited us.
I have already introduced some of the poetical productions of this
epoch, and I only wish they had all been preserved. A never failing
excitement in the happy season of love, heightened by the beginning
of care, gave birth to songs, which throughout expressed no
overstrained emotion, but always the sincere feeling of the moment.
From social songs for festivals, down to the most trifling of
presentation-verses—all was living and real and what a refined
company had sympathized in; first glad, then sorrowful, till finally
there was no height of bliss, no depth of woe, to which a strain was
not devoted.
All these internal feelings and outward doings, so far as they were
likely to vex and pain my father, were by my mother's bustling
prudence skilfully kept from him. Although his hope of seeing me
lead into his house, that first one (who had so fully realised his ideas
of a daughter-in-law) had died away, still this "state-lady," as he
used to call her in his confidential conversations with ms wife, would
never suit him.
Nevertheless he let matters take their course, and diligently occupied
himself with his little Chancery. The young juristic friend, as well as
the dexterous amanuensis, gained continually more and more of
influence under his firm. As the absentee was now no longer missed
there, they let me take my own way, and sought to establish
themselves firmly upon a ground on which I was not destined to
thrive.
Fortunately my own tendencies corresponded with the sentiments
and wishes of my father. He had so great an idea of my poetic
talents, and felt so personal a pleasure in the applause which my
earliest efforts had obtained, that he often talked to me on the
subject of new and further attempts. On the other hand, I did not
venture to communicate to him any of these social effusions and
poems of passion.
As, in Götz von Berlichingen, I had in my own way
mirrored forth the image of an important epoch of Plan of Egmont.
the world, I now again carefully looked round for
another crisis in political history of similar interest. Accordingly the
Revolt of the Netherlands attracted my attention. In Götz, I had
depicted a man of parts and energy, sinking under the delusion that,
in times of anarchy, ability and honesty of purpose must have their
weight and influence. The design of Egmont was to shew that the
most firmly established institutions cannot maintain themselves
against a powerful and shrewdly calculating Despotism. I had talked
so earnestly with my father about what the piece ought to be, and
what I wanted to do, that it inspired him with an invincible desire to
see the plan which I had already worked out in my head, fairly set
down on paper, in order to its being printed and admired.
In earlier times, while I still hoped to gain Lili's hand, I had applied
myself with the utmost diligence to the study and practice of legal
business, but now I sought to fill the fearful gulf which separated me
from her, with occupations of more intellect and soul. I therefore set
to work in earnest with the composition of Egmont. Unlike the first
Götz von Berlichingen, however, it was not written in succession and
in order; but immediately after the first introduction I went at once
to the main scenes without troubling myself about the various
connecting links. I made rapid progress, because my father, knowing
my fitful way of working, spurred me on (literally and without
exaggeration) day and night, and seemed to believe that the plan,
so easily conceived, might as easily be executed.

TWENTIETH BOOK.

Kraus—Daemonic Influence—Heidelberg—Departure for Weimar

And so I got on rapidly with my "Egmont;" and while I found in this


some alleviation of my wounded passion, the society of a clever
artist also helped me through many wearisome hours. And thus, as
had often before been the case, a vague desire of practical
improvement brought me a secret peace of mind, at a time when it
could scarcely be hoped for.
George Melchior Kraus, who had been born at Frankfort, but educated
in Paris, having just returned from a short tour to the north of
Germany, paid me a visit, and I immediately felt an impulse and a
need to attach myself to him. He was a cheerful merry fellow, whose
light joyous disposition had found its right sphere in Paris.
At that time Paris promised a pleasant welcome for Germans; Philip
Hackert was residing there in credit and opulence; the true German
style in which, both in oil and water-colors, he faithfully executed
landscapes after nature, met with great favor, as contrasted with the
formal mannerism into which the French had fallen. Wille, in high
esteem as a copperplate engraver, supported and made German
excellence more widely known. Grimm, already an artist of some
influence, rejoiced to help his countrymen. Pleasant excursions, in
order to take original sketches from nature were constantly
undertaken, in which much of undoubted excellence was either
executed or designed.
Boucher and Watteau, both of them artists born, whose works,
though fluttering in the style and spirit of the time, were always
highly respectable, were favorably inclined to the new school, and
even took an active part in their excursions, though only for the sake
of amusement and experiment. Greuze, living quietly by himself in his
family circle, and fond of representing such domestic scenes,
seemed delighted with his own works, held an honored and easy
pencil.
All these several styles our townsman Kraus was able to take up and
blend with his own particular talent; he formed himself in school
after school, and was skilful in his portrait-like delineations of family
and friendly gatherings; equally happy was he in his landscape
sketches, which cordially commended themselves to the eye by their
clear outlines, massive shadows, and agreeable coloring. The inward
sense was satisfied by a certain naïve truth, while the admirer of
artistic skill was especially pleased with the tact by which he
arranged and grouped into a picture what he had copied singly from
nature.
He was a most agreeable companion; a cheerful equanimity never
failed him; obliging without obsequiousness, reserved without pride,
he was everywhere at home, everywhere beloved, the most active,
and, at the same time, the most manageable of all mortals. With
such talents and of such a disposition, he soon won the favor of the
higher circles; but he was especially well received at the castle of the
Baron von Stein, at Nassau on the Lahn, whose accomplished and
lovely daughter he assisted in her artistic studies, and in many ways
enlivened the whole circle.
Upon the marriage of this excellent lady to the Count von Werther,
the newly wedded couple took the artist with them to Thuringia,
where the Count possessed a large estate, and thus he got to
Weimar. His acquaintance was immediately sought, his talents were
appreciated—and a wish expressed that he would fix his permanent
abode there.
Obliging as he was to everybody, upon his return at this time to
Frankfort, he stimulated my love of art, which had been contented
with merely collecting, and to making practical essays. The
neighbourhood of the artist is indispensable to the Dilettante, for the
latter sees all that is wanting in himself supplied by the former; the
wishes of the amateur are fulfilled in the artist.
By a certain natural talent, assisted by practice, I succeeded pretty
well in an outline, and I could give the shape of all that I saw before
me in nature; but I wanted the peculiar plastic power, the skilful
industry, which lends a body to the outline by well-graduated light
and shade. My copies were rather remote suggestions of the real
form, and my figures like those light airy beings in Dante's
Purgatory, which, casting no shadow themselves, fled affrighted at
the shadows of actual bodies.
Lavater's fishing for physiognomical treasures—for so we may well
designate the importunate urgency with which he called upon all
men, not only to observe physiognomies, but also practically to
make, be it artistic or most bungling attempts at copying faces, led
me into the habit of taking the portraits of all my friends on grey
paper, with black and white chalk. The likeness was not to be
mistaken, but it required the hand of my artistic friend to make them
stand out from the dark background.
In turning over and looking through the rich
portfolio of drawings which the good Kraus had Kraus the Artist.
taken during his travels, we had most pleasant talk
together when he came to the sketches of scenes and persons in
and about Weimar. On such paintings I, too, was glad to dwell, and
you may imagine that it must have been flattering to the young
man, to see in so many pictures only the text which was to lead to a
circumstantially repeated exclamation: they would be glad to see
him there. With much grace he would imitate the different persons
whose portraits he had taken and impersonate the greetings and
invitations he had received. One very successful oil-painting
represented the musical director, Wolf, at the piano, with his wife
behind him preparing to sing; and this gave the artist opportunity to
assure me in earnest terms, of the warm welcome this worthy pair
would give me. Among his sketches were several of the wood and
mountain scenery around Bürgel. Here an honest forester, more
perhaps to please his pretty daughters than himself, had by means
of bridges, railings, and mossy paths, opened pleasant and sociable
walks through the rough masses of rocks, thickets, and plantations.
In one of these beautiful promenades he had painted the fair
damsels in white dresses, and not without their attendant cavaliers.
In one of these you immediately recognized Bertuch, whose serious
designs upon the oldest daughter were openly avowed; and Kraus
was not offended if you ventured to refer a second youth to himself,
and guessed his growing attachment to the sister.
Bertuch, as the pupil of Wieland, had so distinguished himself in
science and in business, that already appointed private secretary of
the Duke, he had the best possible prospects before him. From him
we passed to Wieland and talked at length of his rectitude, and
cheerfulness, and kindly disposition; his fine literary and poetical
designs were dwelt upon, and allusions were made to the influence
of the Merkur throughout Germany; many other names of literary,
political, or social distinction were also mentioned, and among them.
Musæus, Kirms, Berendis, and Ludecus. Of women, the wife of Wolf,
and a widow Kotzebue, with a lovely daughter and a bright boy,
were, among many others, characterized and extolled. Everything
seemed to point to a fresh and active life of literature and art.
And so, by degrees, were exhibited all the various elements upon
which the young Duke was, on his return, to work. His mother and
guardian had prepared this state of things, while, as regarded the
introduction of more important measures, all that, in accordance
with the duty of such provisional governments, was left to the
judgment and decision of the future sovereign. The sad ruin caused
by the burning of the palace was already looked upon as furnishing
occasion for new improvements. The mines at Ilmenau, which had
stopped working, but which, it was asserted, might again be made
profitable by going to the great expense of repairing the deep shaft;
—the university at Jena, which was somewhat behind the spirit of
the age, and was consequently threatened with the loss of some of
its most able teachers,—and many other matters, roused a noble
common interest. Already were looks cast around for persons, who,
in the upward struggle of Germany, might be qualified to further
such various designs for good, and the prospect seemed as fresh as
the vivacity and energy of youth could desire. And if it seemed sad
to bring a young princess not to a home, of a suitable princely
dignity, but to a very ordinary dwelling built for quite a different
object; still such beautifully situated and well contrived country-
houses as Ettenburg, Belvedere, and other delightful pleasure-seats,
gave enjoyment for the present, and also a hope that the life of
nature thus rendered necessary, might lead to profitable and
agreeable occupations.
In the course of this biography, we have circumstantially exhibited
the child, the boy, the youth, seeking by different ways to approach
to the Suprasensible first, looking with strong inclination to a religion
of nature; then, clinging with love to a positive one; and, finally,
concentrating himself in the trial of his own powers, and joyfully
giving himself up to the general faith. Whilst he wandered to and
fro, space which lay intermediate between the sensible and
suprasensible regions, seeking and looking about him, much came in
his way which did not appear to belong to either, and he seemed to
see, more and more distinctly, that it is better to avoid all thought of
the immense and incomprehensible.
He thought he could detect in nature—both animate and inanimate,
with soul or without soul—something which manifests itself only in
contradictions, and which, therefore, could not be comprehended
under any idea, still less under one word. It was not godlike, for it
seemed unreasonable; not human, for it had no understanding; nor
devilish, for it was beneficent; nor angelic, for it often betrayed a
malicious pleasure. It resembled chance, for it evolved no
consequences; it was like Providence, for it hinted at connexion. All
that limits us it seemed to penetrate; it seemed to sport at will with
the necessary elements of our existence; it contracted time and
expanded space. In the impossible alone did it appear to find
pleasure, while it rejected the possible with contempt.
To this principle, which seemed to come in
between all other principles to separate them, and The Daemonic—
Egmont.
yet to link them together, I gave the name of
Daemonic, after the example of the ancients and of those who, at
any rate, had perceptions of the same kind. I sought to screen
myself from this fearful principle, by taking refuge, according to my
usual habits, in an imaginary creation.
Among the parts of history which I had particularly studied with
some care, were the events which have made the United
Netherlands so famous. I had diligently examined the original
sources, and had endeavoured, as far as possible, to get my facts at
first hand, and to bring the whole period vividly before my mind's
eye. The situations it presented appeared to me to be in the highest
degree dramatic, while, for a principal figure, around whom the
others might be grouped with the happiest effect, there was Count
Egmont, whose greatness as a man and a hero was most
captivating.
But for my purpose it was necessary to convert him into a character
marked by such peculiarities as would grace a youth better than a
man in years, and an unmarried man better than the father of a
family; and one independent, rather than one, who, however freely
disposed, nevertheless restrained by the various relations of life.
Having thus, in my conception of Egmont's character, made him
youthful, and set him free from all domestic restraints, I ascribed to
him unlimited enjoyment of life and its pleasures, boundless self-
reliance, a gift of drawing all men to himself, and consequently also
of winning the favor of the people, and which, while it inspired a
princess with a silent, and a young child of nature with an avowed
passion, won for him the sympathy of a shrewd statesman, and even
the loving admiration of the son of his great adversary.
The personal courage which distinguishes the hero
is the foundation upon which his whole character The Daemonic
Influence in Life.
rests, the ground and soil from which it sprung. He
knows no danger, and willingly is blind to the greatest when it is
close at hand. Surrounded by enemies, we may, at any rate, cut our
way through them; the meshes of state policy are harder to break
through. The Daemonic element, which is in play on both sides, and
in conflict with which the lovely falls while the hated triumphs; and,
above all, the prospect that out of this conflict will spring a third
element, which will answer to the wishes of all men this perhaps is
what has gained for the piece (not, indeed, immediately on its first
appearance, but later and at the right time), the favor which it now
enjoys. Here, therefore, for the sake of many beloved readers, I will
anticipate myself, and as I know not whether I shall soon have
another opportunity, will express a conviction which, however, I did
not form till a considerable period subsequent to that of which I am
now writing.
Although this Daemonic element can manifest itself in all corporeal
and incorporeal things, and even expresses itself most distinctly in
animals, yet, with man, especially does it stand in a most wonderful
connexion, forming in him a power which, if it be not opposed to the
moral order of the world, nevertheless does often so cross it that
one may be regarded as the warp, and the other as the woof.

You might also like