The First Line of Code: Android Programming with Kotlin Lin Guo - Quickly download the ebook to explore the full content
The First Line of Code: Android Programming with Kotlin Lin Guo - Quickly download the ebook to explore the full content
com
https://ebookmeta.com/product/the-first-line-of-code-
android-programming-with-kotlin-lin-guo/
OR CLICK HERE
DOWLOAD EBOOK
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
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
Learning Resources
vii
viii Contents
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
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
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.
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.
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.
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.
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.
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!
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
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
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.
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
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
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
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
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
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
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
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
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>
<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
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.
• 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>
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:
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 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.