0% found this document useful (0 votes)
11 views

The First Line of Code: Android Programming with Kotlin Lin Guo download

The document provides information about the book 'The First Line of Code: Android Programming with Kotlin' by Lin Guo, which serves as a comprehensive guide 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 knowledge level. Additionally, it includes links to other related eBooks and resources for further learning.

Uploaded by

spizamollic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

The First Line of Code: Android Programming with Kotlin Lin Guo download

The document provides information about the book 'The First Line of Code: Android Programming with Kotlin' by Lin Guo, which serves as a comprehensive guide 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 knowledge level. Additionally, it includes links to other related eBooks and resources for further learning.

Uploaded by

spizamollic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

The First Line of Code: Android Programming with

Kotlin Lin Guo install download

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

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Head First Android Development: A Learner's Guide to


Building Android Apps with Kotlin 3rd Edition Dawn
Griffiths

https://ebookmeta.com/product/head-first-android-development-a-
learners-guide-to-building-android-apps-with-kotlin-3rd-edition-
dawn-griffiths/

Learn Android Studio 3 with Kotlin: Efficient Android


App Development 1st Edition Ted Hagos

https://ebookmeta.com/product/learn-android-studio-3-with-kotlin-
efficient-android-app-development-1st-edition-ted-hagos/

Learn Kotlin for Android Development: The Next


Generation Language for Modern Android Apps Programming
1st Edition Peter Späth

https://ebookmeta.com/product/learn-kotlin-for-android-
development-the-next-generation-language-for-modern-android-apps-
programming-1st-edition-peter-spath/

Cold as Ice Harpsburg Rangers 1 1st Edition Bonnie


Poirier

https://ebookmeta.com/product/cold-as-ice-harpsburg-
rangers-1-1st-edition-bonnie-poirier/
Bear for the Holidays Zoe Chant

https://ebookmeta.com/product/bear-for-the-holidays-zoe-chant/

Four Lost Cities A Secret History of the Urban Age 1st


Edition Annalee Newitz

https://ebookmeta.com/product/four-lost-cities-a-secret-history-
of-the-urban-age-1st-edition-annalee-newitz-2/

Aristotle on Shame and Learning to Be Good 1st Edition


Marta Jimenez

https://ebookmeta.com/product/aristotle-on-shame-and-learning-to-
be-good-1st-edition-marta-jimenez/

The Other Face of Battle : America's Forgotten Wars and


the Experience of Combat 1st Edition Wayne E. Lee

https://ebookmeta.com/product/the-other-face-of-battle-americas-
forgotten-wars-and-the-experience-of-combat-1st-edition-wayne-e-
lee/

The Practice Of Market Research From Data To Insight


Fifth Edition Yvonne Mcgivern

https://ebookmeta.com/product/the-practice-of-market-research-
from-data-to-insight-fifth-edition-yvonne-mcgivern/
How to Understand Quantum Mechanics 1st Edition John P
Ralston

https://ebookmeta.com/product/how-to-understand-quantum-
mechanics-1st-edition-john-p-ralston/
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
1.3 Creating Your First Android Project 27

cannot be used by this app. versionCode is used to specify the project version and
versionName is used to specify the project version name. At last,
testInstrumentationRunner is used to start the JUnit tests which are created to ensure
the app can work as expected.
After the defaultConfig closure, let’s look at the buildTypes closure. This closure
is used to specify the configuration for the build file which usually has two
sub-closures: debug and release. Debug closure is used to specify the configuration
for the debug version of installer and release closure will specify the configuration
for production version of installer. Notice that debug closure can be omitted thus we
only see the release closure here. In the release closure, minifyEnabled is used to
specify if we need to obfuscate the code or not. proguardFiles is used to specify the
file with obfuscating rules. Here it specifies two files. The proguard-android-opti-
mize.txt file is under <Android SDK>/tools/proguard directory and has general
obfuscation rules for all projects. The proguard-rules.pro is under the root directory
of current project which can be used to write the obfuscating rules for the current
project. It is worth noting that all the installers generated by directly running Android
Studio build and run are debug version. We will learn how to build the production
version in Chap. 15.
That’s all for the android closure. Next is the dependencies closure which can
specify all the dependencies of the current project. There are three types of depen-
dency: local binary dependency, local library module dependency, and remote
binary dependency. Local binary dependency can add dependency to local jars or
directories; local library dependency can be used to add dependency to local lib
modules; remote dependency can be used to add dependency to the open-source
projects in jcenter.
In dependencies closure, implementation fileTree is a local binary dependency, it
will add all the files under libs directory with .jar suffix to the current project’s build
path. Implementation is for remote binary dependency and android.appcompat:
appcompat:1.1.0 is a standard remote dependency lib. Androidx.appcompat is the
domain name which is used to distinguish from libs from other companies;
appcompat is the project name which is used to differentiate from the libs in the
same company; 1.1.0 is the version number that can differentiate the same lib with
different versions. After adding this, Gradle will check if cache of this lib exists
locally, if not, then it will download the lib and add to the build path. We don’t have
local lib dependency which has the format of implementation project + lib name. For
example, if we have lib module with name helper, then in order to add dependency
on this lib, we just need to add implementation project(‘:helper’). We will cover
more detail on this in the last chapter. The testImplementation and
androidTestImplementation are used for testing which we don’t need for now.
28 1 Your First Line of Android Code

1.4 Mastering the Use of Logging Tools

Now you’ve built your first Android app and been familiar with the structure of
Android project and executing mechanism. Before we dive into more advanced
topics, I’d like to cover log tools in Android since they will help you profoundly in
your Android development journey.

1.4.1 Using Android Log Tool

The log class in Android is Log(android.util.Log) which provides the following


5 methods to print logs in the console. Here the verbosity is in descending order for
these methods.
• Log.v(): used for the least meaningful information with the highest level of
verbosity.
• Log.d(): used for the debugging information which should help you debug the
app and investigate issues.
• Log.i(): used for important information like data that can help analyze the user
behavior.
• Log.w(): used to print some warnings which means there is potential risks and
need some attention to investigate into the issue.
• Log.e(): used to print error information such as the error info in the catch
statement. When there are error info logs, it usually means your app has some
serious issue that needs to get fixed immediately. This should have the least
verbosity.
These 5 methods have their own overriding methods which shouldn’t be difficult
to understand and now let us try to use this tool in our HelloWorld project.
Open MainActivity and add log statement in onCreate() method as shown below:

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d("MainActivity", "onCreate execute")
}
}

Log.d() takes two params: the first param is tag which usually is the name of the
current class and is used to filter the information; the second param is msg which is
the content that needs to be printed.
Now reinstall and run HelloWorld. You can do so by clicking the Run button or
use the shortcut Shift + F10(control + R in Mac). After the app finishes running, click
1.4 Mastering the Use of Logging Tools 29

Fig. 1.26 Information in Logcat

the Android Monitor tab at the bottom toolbar. In Logcat you can see the printed
information as shown in Fig. 1.26.
From the logs, you can see the content you specified, tag, package name, time
stamp, and app process number.
You will find that Logcat has the logs coming from HelloWorld and other apps. I
will cover how to filter out the logs that are coming from our own app in the next
section.
Another thing worth noting is that you just wrote your first line of Android code,
finally!

1.4.2 Log Vs Println()

Lots of Java beginners use System.out.println() everywhere to print the information


to help them debug and the corresponding method in Kotlin is println(). However, it
is not recommended in more professional projects. If you use it in your company
project, you will very likely face backlash in code review.
The reason why we shouldn’t use println() is because there is nothing it can offer
besides convenience. It is convenient because you just need to type “sout” and auto
completion can fill the missing characters for you which should be one reason why
beginners love to use it. However, you cannot control turning on and off of this
method, also you cannot add tag for filtering purpose nor does this method provide
information with different levels of verbosity control ...
Log class is not the silver bullet to solve every problem, but it is a tool with decent
functionality. Let us take look at what the combination of Log and Logcat can do.
First, you can add filter easily in Logcat, and then you can see all the filter options
in Fig. 1.27.
There are three filter options for now, Show only selected application and No
filters are self-explanatory; Firebase is a platform provided by Google and we can
ignore it for now. Now let us add our own filter.
Click “Edit Filter Configuration” option, a window to show configuration for
filter will pop up. We can name this filter data and let it filter the logs with tag named
with data as shown in Fig. 1.28.
Click “OK” and you will find that now we have a filter named data. After
selecting this filter, the logs that get printed in onCreate() are gone, this is because
this filter will only show the logs that with tag value equals data. Now update the log
30 1 Your First Line of Android Code

Fig. 1.27 Filter options in


Logcat

Fig. 1.28 Filter


configuration window

Fig. 1.29 Verbosity levels


in Logcat

tag to data then reinstall and rerun the app, you should be able to see the log in
Logcat.
For a few lines of logs, this feature doesn’t seem very useful. However, when app
prints hundreds or even thousands of lines of logs, you will need this feature,
desperately.
Now let’s take look at the verbosity level control in Logcat. Logcat has the same
verbosity levels as mentioned previously as shown in Fig. 1.29.
When we choose Verbose which has the highest level of verbosity. This means
that no matter which Log method we use to print the log, the log will show
up. However, if we choose Debug, only logs that are at Debug or above level will
show up, so on so forth. You can try it out by choosing Info, Warn or Error in Logcat
and you will find that the logs we added won’t show up since they used Log.d()
method.
1.5 Summary 31

Fig. 1.30 Keyword


input box

The verbosity level control for logs can help you locate the logs you want much
quicker. Imagine thousands of lines of logs in your screen and you just need to select
Error in Logcat, then only error logs will show up.
Lastly, let us take look at keyword filtering. If you cannot identify the logs you
want even with the combination of filter and verbosity level control, then you can use
keyword filtering as shown in Fig. 1.30.
We can type in the keyword in the input box and then only those logs that have
matches with the keyword will show up. It is worth noting that regex is supported
here for more advanced filtering.
That is everything for using log tools in Android, I will stop here and you can
continue the exploration of using Logcat by yourself. Let us summarize what we
have learned in this section.

1.5 Summary

You must feel fulfilled and happy now. You should because you’ve already become
a real Android developer. In this chapter, you first learned Android system, set up the
Android development environment, built your first Android project, and then went
over the structure of the Android project folders and the execution process of the app.
At the end of the chapter, you also learned how to use the log tools in Android. Isn’t
it productive time?
However, there is a huge difference between an Android developer and an
efficient Android developer. Before we start the next chapter, get some rest and
digest the knowledge here and get ready for the next chapter.
Other documents randomly have
different content
Nyanza, discovered the Mwuta Nzige (Lake Albert Edward), and
crossed Africa from east to west, starting from Zanzibar and
travelling down the Lualaba from the point where Livingstone had
left it to its mouth, thus proving it to be the upper level of the
Congo. This great journey opened up the hitherto unknown country
in the centre of Africa, and led directly to the formation of the Congo
Free State. Stanley had been preceded at Nyangwe, the point of
departure for the voyage down the Congo, by Lovett Cameron, who
failed, however, to follow the river throughout its course, and
reached the coast to the south of its mouth. In 1884 Joseph
Thomson supplemented Stanley’s work by his journey to Mounts
Kilimanjaro and Kenya through Masailand to Victoria Nyanza.
Wissmann and other German explorers (1881–6) did much for a
knowledge of the great southern tributaries of the Congo, while
Wissmann in 1881–2 crossed the continent from west to east. It has
been frequently crossed since. Stanley’s expedition up the Congo to
rescue Emin Pasha (1887–89) opened up the great Central Africa
forest with its pigmies, extended our knowledge of Lake Albert
Edward and its outlet the Semliki, which flowed into the Albert
Nyanza, and revealed the great snowy range of Ruwenzori, which
was ascended and mapped by the Duke of the Abruzzi in 1906.
While the problems of Central Africa were thus being elucidated,
the exploration of the nine great rivers which form the Bahr-el-
Ghazal, the chief tributary of the Nile, was attracting much attention,
the most valuable work being done by Georg Schweinfürth, who
mapped the river with high accuracy. The Nile above Gondokoro was
also surveyed by English officers; the Sahara and the Sudan were
widely explored by G. Rohlfs and G. Nachtigal between 1860 and
1875, and the connection of the river Welle with the Congo system
was established by W. Junker, who also travelled in the Sudan from
1875 to 1886. The British during this period were pushing their way
northward from South Africa, and emigrants were flocking to the
goldfields and diamond mines. The French have spread their
explorations over the Sahara and their territories in the Sudan and
West Africa. From the date of Stanley’s return African history
underwent a rapid change. The period of driving the main lines of
exploration through the continent was over, and a new era began in
which branch lines could be laid down, and colonial expansion could
take place along them. The continent is now partitioned among the
European Powers, and has been more or less provisionally mapped;
but it will take long years of survey and scientific investigation before
its features, its resources, its peoples, and its possibilities are
adequately known.
Chapter XII.

THE NINETEENTH CENTURY AND AFTER:


ASIA AND AUSTRALIA

The beginning of the nineteenth century was signalized by the


initiation of the great trigonometrical survey of India, and the first
half-century was a period of much important geographical and
anthropological work within that empire, but to no great extent
beyond its boundaries, though in 1808 a mission penetrated to the
sources of the Ganges, and Baluchistan and Afghanistan were in
some part explored by officials of the East India Company. But the
physical problems of the heart of the continent were left to a later
period—those, for instance, concerned with the trans-Himalayan
region (as viewed from India), including Tibet, eastward that region
so important in the hydrography of the continent, where the river
systems of China and Burma take their rise, northward the deserts
of Mongolia and Turkestan, westward the nodal mountain-region of
the Pamirs, and the area which long concealed the sources of the
Brahmaputra (Tsanpo) and the rivers of Punjab. In spite of the
endeavours of the Tibetans to hold inviolate the secrets of their land
—in great measure successful so far as their capital, Lhasa, was
concerned—the Indian native surveyors, such as Nain Singh,
Krishna, and Ugyen Gyatso, were able to penetrate the country, and
even Lhasa itself; their work covered the period 1863–82. And the
last quarter of the century provides a wonderful record of continuous
exploration in Tibet, as will appear from the mere quotation of
names and dates—P. Bonvalot and Prince Henry of Orléans, 1886–
87; W. W. Rockhill, 1888 and 1891; Hamilton Bower, 1891–92;
Dutreuil de Rhins and F. Grenard, 1893–94; St. George Littledale,
1895; Captains W. S. Wellby, 1896, and H. H. P. Deasy, 1896, whose
work was afterwards extended by Captain C. G. Rawling and by Sir
M. A. Stein; and Sven Hedin, 1896–98, 1899–1902, 1906–08, whose
last journey revealed the existence, long suspected, of the great
mountain system north of the upper Tsan-po. This list is by no
means exhaustive, nor can be that of the Russians who worked from
the opposite direction, from their own territory; their leader was
Nicolai Prjevalsky, who in 1871–73 and in 1876 worked in the
Tsaidam region and made the first contribution to the mapping of
the important hydrographical area above referred to, and in 1879
studied the vast physical changes which have taken place in Central
Asia within historic times, and form one of the most remarkable
geographical problems in the world. He continued his work in 1883–
85, and was followed by Pevtsov and Roborovsky (1889 and 1894),
P. K. Kozlov, Potanin, and many others. The names of Russian
scientists, such as Baron A. Kaulbars and L. Griesbach, are also
associated with the problems of the Aral and Caspian depressions.
The former extensions of human settlement over areas now covered
by the Central Asian deserts has been brought to light in great
measure through the researches of Sven Hedin, and especially of Sir
M. A. Stein. The general result of all these investigations has been to
modify profoundly, even during the present generation, preexisting
ideas of the physical geography of the central region. Nor should we
overlook the work of recent travellers in China proper, a broad
canvas on which outlines had been sketched earlier; but details
remained, and still in great part remain, to be filled in, though
Ferdinand Baron von Richthofen, in the course of his seven journeys
in 1868–72, left few districts entirely unvisited.
The problem of the former existence of flourishing communities
in areas now desert, and of the causes of the change, has a partial
counterpart in southern Arabia. The modern period of Arabian
exploration began earlier than that of Central Asia. The journeys of
J. Halévy (1869), E. Glaser (1889), and J. T. Bent (1893) in the
south were primarily archæological in purpose. In other parts of the
peninsula the work of J. L. Burckhardt (1815), Sir R. F. Burton,
Captain G. F. Sadlier, W. G. Palgrave, Charles Doughty, Wilfrid Blunt,
C. Huber, Musil, Leachman, and others, has made it possible to lay
down at least the position of the chief towns and settlements, and
the main physical outlines, with close accuracy, save in the Dahna or
great desert of the southern interior, which remains untrodden.
The detailed exploration of Australia began from Sydney, the
earliest settlement, and was directed along the coast rather than
towards the interior, the penetration of which was difficult. George
Bass, after a short expedition inland, was accompanied by Matthew
Flinders in exploring the coast of New South Wales as far as the
George River and Hat Hill towards the end of the eighteenth
century; in 1797–98 Bass Strait was found to separate Tasmania
from the mainland, and that island was circumnavigated. Bass was
subsequently lost in South America; but Flinders extended the work
in 1801–03, when, having sailed from England, he worked from King
George Sound at the south-west of Australia right round the south,
east, and north coasts as far as Arnhem Bay, west of the Gulf of
Carpentaria, and would have accomplished more but for the
unseaworthiness of his ship. Flinders was not only a competent
explorer, but also a man of theories: he took the limestone cliffs of
the Great Australian Bight (south coast) for coral reefs, and when he
entered Spencer Gulf he thought of a northward strait connecting
with the Gulf of Carpentaria, and conceived an Australian
archipelago; nor was he wholly disabused until he had definitely
located the heads of both gulfs. A number of important inlets, such
as Port Phillip, Keppel Bay, and Port Bowen, were thoroughly
investigated by him, and he also surveyed the Great Barrier Reef.
And the substitution of the name of Australia for New Holland is due
to a suggestion of his. His unfinished survey of the western shores
was completed by Captain P. P. King in voyages between 1817 and
1822.
The accident of a drought in 1813 drove some of the Sydney
settlers to look for new pastures in the hinterland. The divide
between the short eastward and the long westward drainage
systems was surmounted with difficulty; a road to the point where
the town of Bathurst afterwards grew up was promptly made, and
an arresting geographical problem confronted the investigators when
the westward-flowing rivers Macquarie and Lachlan were found.
Lieutenant Oxley, R.N., attempting to follow the Lachlan in 1815,
was presently brought to a halt by great swamps. He struck south to
avoid them, and narrowly missed discovering the Murrumbidgee
river, before he turned back to carry to Sydney the conviction that
the westward drainage generally was lost in swamps fringing an
inland sea. Cunningham found a route from this coast up to the rich
Liverpool Plains, towards the north of New South Wales, in 1823; but
for the most part exploration was temporarily directed to the south-
west, and Hamilton Hume and Hovell in 1824–25 took an inland
route from New South Wales to the south coast on the west side of
Port Phillip. This inlet was not recognized by them; they returned to
report that they had seen the coast-land, and found it good, further
to the east at Western Port; settlers who visited that district on their
recommendation were disappointed, and the development of the
Victoria coast-lands received a set-back in consequence of this error.
Cunningham in 1828 opened the route from the coast at Brisbane to
the downs of the south Queensland hinterland. In the same year a
new phase was entered in the solution of the problem of the far
interior, when Charles Sturt, carrying with him Oxley’s conviction of
the existence of an inland sea, journeyed inland at a season of
drought to find the Macquarie river losing itself on the dry plains,
and the Darling flowing salt. He attributed this fact to an admixture
of sea-water, and set down the interior of the continent as a desert.
In the following year he settled the problem of the drainage of the
Murrumbidgee, Lachlan, and Murray rivers by following them to the
mouth of the Murray in Lake Alexandrina (south coast); and
although he now held that the waters of the Darling were included
(as they are) in this system, it was still doubted whether there was a
divide between north and south flowing waters about the central
latitude of New South Wales, where, in the interior, high ground was
known to exist. Sir Thomas Mitchell settled this question by a great
journey in 1836, which, among other results, immediately threw
open to settlement the fertile country about Port Phillip, hitherto, as
we have seen, neglected through the misunderstanding of Hume
and Hovell.
The larger problems of Australian geography were thus early
settled, though there was (as even now there is in some parts) a
multitude of details to be filled in. But the leading questions awaiting
solution by explorers now become economic rather than purely
geographical. Thus we find Dr. Leichhardt’s first expedition (1844),
from Moreton Bay in southern Queensland by the Burdekin, Mitchell,
and Roper rivers to Port Essington, inspired by the conception of an
overland route between Sydney and a northern seaport. He was lost
(and the mystery of his fate was never solved) in 1848 in attempting
a crossing of the continent from east to west, and Kennedy’s
expedition in the same year, in attempting to cross northern
Australia, also met with disaster, where A. C. Gregory succeeded in
1855–56. The penetration of the interior from the south and the
crossing to the north had attracted travellers before this; Eyre in
1840 had discovered the series of salt lakes and swamps which he
lumped together under the name of Lake Torrens, while Sturt in
1845 added little to Eyre’s discoveries, and, after failing to penetrate
the Stony Desert to the north, put a temporary period to
explorations in that quarter. Babbage in 1856 and Parry in the
following year obtained more accurate knowledge of the Lake
Torrens region, and Goyder in 1857 reported a great freshwater lake
which was found later to have been conceived out of some shallow
pools and visions of the mirage. J. M. Stuart’s six expeditions from
south to north in 1858–61 added much to exact knowledge; that of
Robert Burke and William Wills in 1860–61, ill-managed as it was
and ending in the death of the leaders, obtained a fame in excess of
its scientific value; but other expeditions sent in search of it achieved
better results, and incidentally made clear the danger of assessing
the worth of some of the inland districts on the report of one
traveller who might have come upon them at an unfavourable
season. Thus J. McKinlay in 1861 brought word of fertile lands which
Sturt had condemned as desert. The many journeys through the
interior of Western Australia—such as those of J. S. Roe (1836), the
brothers Gregory, H. M. Lefroy (1863), Sir J. Forrest (various
expeditions in and after 1869), Warburton (1873), and Ernest Giles
(first crossing from Adelaide to Perth by an inland route, 1875)—
though often of extreme importance from an economic point of
view, whether concerned with the discovery of pastoral lands or of
gold or other mineral fields, can only be referred to here as having
gradually opened up the detailed knowledge of this part of the
continent, and as having redeemed it in part from a reputation for
complete inhospitality, until we have now a trans-continental railway
planned to connect the systems of south and of western Australia.
The exploration of the Kimberley and north-western areas of the
state was delayed until the latter half of the last century.
Chapter XIII.

THE NINETEENTH CENTURY AND AFTER:


THE POLES

(a) Arctic
Following the new enthusiasm for Arctic exploration undertaken for
purely scientific purposes, the British Government despatched three
expeditions between 1773 and 1779. The first, under Captain
Phipps, was stopped by ice off the north-west of Spitsbergen; the
second, that of James Cook with the vessels Discovery and
Resolution, sent to search for either a north-west or a north-east
passage by the Bering Sea route, met, as has been seen (Chapter
VIII.), with a measure of the success characteristic of his work, but
his death at Hawaii put an end to the hope that further research in
the Arctic lay before him, and the voyage continued under the
command of Captain Clarke was carried only a little north of the
70th parallel in the ice-bound Bering Strait, where Clarke also died.
Till 1815 little was done to elucidate the still unsolved question of
the north-west passage, owing to the disturbed state of Europe and
America, but the offer of a reward (the result of the exertions of Sir
John Barrow in 1818) of £20,000 for the discovery of the passage
and £5,000 for reaching 89° N., led to the sailing of expeditious to
the American Arctic region under Lieut. J. Franklin, Captain Ross,
and Lieut. E. Parry. Ross on his first voyage took Baffin Bay and
Lancaster Sound to be land-locked on the north, and thus missed his
chance of forcing the passage.
Parry in two voyages, on the results of which he gained the
£5,000 reward, succeeded in passing through Lancaster Sound, and
reaching and naming Melville Island, thus proving Baffin’s
discoveries. Meanwhile Franklin attempted to reach the north shores
of America by land; he explored 550 miles of the coast and
discovered and named Cape Turnagain, though he and his party
suffered great privations on the return journey. Then the energies of
explorers were directed towards combining the results obtained by
Parry and Franklin; further stretches of the north coast of America
were explored, and Point Barrow was reached in Bering Strait. In
1829 an expedition was undertaken by Captain John Ross and his
nephew James Clark Ross; the opening of the passage was again
missed (though the most northerly part of America was passed), and
it was not discovered till 1851 by Kennedy on his search for Franklin.
J. C. Ross, however, fixed the position of the north magnetic pole on
this voyage of five years’ duration, and other valuable observations
were made. The work of tracing the northern shores of America was
nearly finished by 1847, chiefly by travellers in the Hudson Bay
Company’s service. During this period the north coast of Siberia had
also been traced almost in its entirety by the Russians, though they
had not succeeded in rounding the most northerly point.
In 1845 Sir John Franklin started on the voyage from which
neither he nor any of his companions returned. It is not known
exactly what he achieved before he was lost, but he came nearer to
accomplishing the north-west passage than anyone before him. The
expeditions of Sir John Richardson, Dr. John Rae, and others, sent by
land in search of his party, filled in the last gap in the northern
coast-line of America. The different expeditions, under McClintock
and others, sent by sea in the fifties for the same purpose not only
decided the fate of Franklin’s party and extended knowledge over a
vast area, but also at last rounded the north of America. The
passage found by Kennedy in 1851 was traversed in 1853 by
McClure, though part of the journey was made by travelling over the
ice. An expedition under Captain Inglefield determined the northern
point of Smith Sound. Elisha Kent Kane extended the knowledge of
Grinnell Land and Greenland towards the north, and opened the way
to others who followed the waterways he discovered. In 1871
Charles Hall sailed 250 miles up Smith Sound and reached the
hitherto inaccessible polar sea; he touched a more northerly point
than had previously been reached by any ship (82° 11´ N.).
Stirred to action by these fine achievements of the Americans,
England sent out the important expedition under Captain George
Nares in 1875 which obtained very valuable scientific observations,
taken on the frozen polar sea, and under Albert Markham reached
the furthest point north yet attained—83° 20´ N.—after battling with
immense difficulties caused by bad conditions of the ice and scurvy.
Meanwhile much good work had been done in the Arctic from the
old world. A purely scientific expedition had been sent to the
Spitsbergen seas as early as 1827 from Norway; but from then till
1858 the work of exploration was chiefly carried on by the men
engaged in the seal-hunting and fishing, in the interests of their
trade. Before 1872, however, several Scandinavian expeditions which
visited Spitsbergen and Greenland brought back valuable scientific
results. The most noteworthy expedition of this period, however, was
Austrian; it was captained by Lieutenant Julius Payer, who had
previously been on an expedition in Greenland. He and Lieutenant
Weyprecht sailed in 1871 to search for the north-east passage. They
were beset by ice off Novaya Zemlya, and drifted till they came to a
mountainous country which they called Franz Josef Land. They
believed it to consist of two large masses of land, instead of
perceiving it to be an archipelago, and much of the country they
thought they saw has been since proved not to exist. Franz Josef
Land was not visited again till 1880, when a large part of it was
surveyed by the Englishman Leigh Smith. The north-east passage
was made in 1879 by A. E. Nordenskiöld, who accomplished the
journey which led so many before him to failure without loss of life
or vessel, and almost in one season. He had made several previous
voyages in Greenland and Spitsbergen; he had also twice
successfully reached the Yenisei through the Kara Sea. Captain
Joseph Wiggins, an Englishman, also made several voyages through
the Siberian seas, which, together with Nordenskiöld’s
accomplishment of the north-east passage (1878–9), proved the
route to the mouth of the Yenisei to be practicable from a
commercial standpoint. Fired by Nordenskiöld’s example, the Danes
made several remarkable journeys to the interior of Greenland.
A new interest was given to polar research by the establishment
of the international circumpolar stations in 1883. The idea was
mooted first by Weyprecht, and eventually twelve expeditions of
various nationalities were sent out to erect observatories at different
points within the polar circle, so that simultaneous and continuous
observations might be taken. A great deal of valuable work was
done. An American expedition, led by Lieutenant A. W. Greely
(1881–4), to Grinnell Land almost perished from starvation.
Greenland was crossed for the first time by Fridtjof Nansen in
1888. In 1886, and again from 1892 to 1895, Robert E. Peary, an
American civil engineer, made several brilliant journeys in Greenland,
and extended the knowledge of the country more than two degrees
to the north. It was Nansen and Peary who were destined to draw
the veil from the great polar area itself, towards which so many
fruitless journeys were made. From 1817 onwards many voyages
were undertaken with the object of reaching the pole—as by Parry,
Scoresby, Markham, and Jackson from England, Nordenskiöld from
Sweden, and Koldewey from Germany. These explorers mostly
started from Spitsbergen; but Nansen worked on an original plan—
that of utilizing the drift of ice, which had been proved to take place
right across the polar sea, to carry his ship with it. The plan was so
far successful that the Fram passed from the New Siberian islands
right over to Spitsbergen in three years, without, however, reaching
a higher latitude than 85° 55´ N. Nansen, with Lieutenant Johansen,
made a dash northwards from this point, reaching 86° 5´ N., the
“farthest north” attained up to that date; he met with Frederick
Jackson’s expedition in Franz Josef Land, and returned safely to
Norway. This brilliant journey led to no discovery of land in the polar
basin, which proved to consist of a sea of great depth, increasing
towards the pole. The Duke of Abruzzi’s expedition in 1899 reached
86° 34´ N.
Meanwhile much good work was being done in other directions
in extending Arctic research. Franz Josef Land was explored, chiefly
by Austrian, British, and American expeditions. Nathorst, a Swede,
circumnavigated the Spitsbergen archipelago in 1898, and
discovered and mapped King Oscar Fjord in Greenland in the
following year. Sverdrup, Nansen’s friend and companion, sailed up
Jones Sound and charted many previously unknown parts in 1899
and the following years. The story of a continent existing to the
north of Bering Strait and extending right across the pole to
Greenland, which was believed by many explorers, was disproved by
De Long in his ill-fated voyage in the Jeannette in 1879, during
which the whole party perished, though the ship’s books were
afterwards found. This voyage and the journeys of the ships sent in
search of De Long proved that north of Siberia lay an ocean dotted
with islands. Much work was done in exploring the New Siberian
Islands by the Russian, Toll, who lost his life in an effort to reach the
most northerly and unknown portion of the group. In 1903–4
Amundsen in the Gjöa undertook an expedition to the North
Magnetic Pole, where he carried out a continuous series of
observations for two years with important scientific results. He
returned by Bering Strait, thus for the first time completing the
navigation of the North-west Passage. The Danes worked hard at
charting the east coast of Greenland, and the outline of the north-
eastern extremity of the country was accurately delineated for the
first time by the expedition of L. Mylius Erichsen (1905–07), on
which he and his companions perished, though their splendid
records and observations were found by a relief expedition. The
crowning achievement of reaching the pole itself was accomplished
in 1909 by Peary, after several previous journeys. He had spent four
consecutive winters in the Arctic regions exploring Smith Sound and
the north of Greenland, from 1899 to 1902; and in 1905 he had
again attempted to reach the pole by Smith Sound and Grant Land,
touching 87° 6´ N. At or near the pole there was no land to be seen,
and the sea was 1,500 fathoms deep. Thus there remains no Arctic
problem of the first magnitude to-day. The main outline of the Arctic
region as a great and deep sea surrounded by the northern shores
of Europe, Asia, America, and Greenland, is known, though there is
still a large portion of the polar basin north of Alaska as yet
untouched by explorers. Here, however, some high authorities
believe that a considerable extent of land remains to be discovered
beyond the Beaufort Sea. Even now maps show a doubtful coast-line
some fifty miles due north of Point Barrow, and in 1913 an
expedition left Canada under Stefansson with the solution of this
problem as its main object.

(b) Antarctic.
In the Antarctic an important voyage, which supplemented
Cook’s work, was undertaken in 1819 by Fabian von Bellingshausen.
He succeeded in sailing half round the Antarctic circle, keeping to
high southern latitudes all the way, and voyaging within the circle for
considerable distances. He found the first land seen within the
Antarctic circle, Peter Island, and, later, Alexander Island; he
discovered the Traverse Islands, and on his return in 1821 touched
at the South Shetland Islands, and met there sealers, by one of
whom, William Smith, the islands had been discovered in 1819. In
the next year, 1822, the South Orkney Islands were found and
named by another sealer. The next voyager was James Weddell, who
reached the highest latitude yet attained, 74° 15’ S., in 1823. At his
highest latitude he had clear sea before him, but was forced to turn
back by the approach of winter, and returned with many interesting
observations and collections. A courageous journey was also made in
1831 by John Biscoe, a sealer, who started out to search for land
from the Sandwich Islands, and succeeded in sailing for some
months within the Antarctic circle in a higher latitude than
Bellingshausen, and sighted land which he named Enderby Land. In
spite of the sufferings he had endured and the death of the greater
number of his crew, he started again in the following year from New
Zealand, discovered Biscoe Islands, and took possession for England
of the land which he could see lying behind them; this was
subsequently named Graham Land. Biscoe was in the employ of an
enterprising London firm, the Enderby Brothers, and after the
remarkable results which he had achieved, they were encouraged to
pursue their policy of directing their captains to embrace every
opportunity of exploration. In 1833 one of them, John Kemp, found
land to the east of Enderby Land, and in 1839 John Balleny
discovered the islands named after him.
About 1835 general interest was aroused in Antarctic problems,
and three expeditions were prepared in England, France, and
America to make magnetic observations, and to explore as far as
possible the southern continent, now at length defined within
reasonable limits. The French expedition, under Dumont d’Urville,
was the first to start in 1838, but achieved little beyond the
exploration of some land south of the South Shetland Islands, which
was called Louis Philippe Land. After wintering in Tasmania, however,
d’Urville decided on making a great effort to reach the south
magnetic pole, and though he failed in this, he found a mountainous
land which he named Adélie Land. The American expedition under
Charles Wilkes did not meet with any great success, hampered as it
was by quarrels among the officers and by unseaworthy ships; but
land was several times sighted at a distance, and on Wilkes’s return
controversy arose as to whether the honour of the discovery of this
southern continent belonged to the French or the American
expedition.
The British expedition under Sir James Ross was the last to
arrive on the scene (in 1841); but it had the advantage of the
others, in that it had been specially equipped for Antarctic
exploration; Ross’s ships could brave dangers from which Wilkes and
d’Urville had been compelled to turn aside. He forced his way
through the pack, and found a range of high mountains trending
southwards, which he called Victoria Land. Following the land he
came to the twin volcanoes, named Erebus and Terror after his two
ships, and was stopped at length by the great ice barrier, running
eastwards. During this remarkable journey Ross reached latitude 78°
4´ S., the highest yet attained. He made two further journeys,
neither so successful as the first, though in 1842 he sighted the land
which was rediscovered, and named King Edward Land, in the
following century. After this no attempt worthy of mention was made
on the south polar region for thirty years. The Challenger expedition
in 1874 was not concerned with the attempt to penetrate very far
south (Chapter XIV.). The voyage in Antarctic waters, however, was
important from the information obtained as to the depth of the
southern ocean and other results which helped to prove the
existence of a considerable mass of land in the Antarctic region. This
information was supplemented by the observations of two of the
international circumpolar stations (to which reference has been
made), which were established in Tierra del Fuego and South
Georgia in 1882; but it was not until many years later that scientific
interest was widely aroused in the problem of the Antarctic
continent, and from 1874 to 1898 the only people to cross the
Antarctic circle were sealers and whalers; but in 1895 C. E.
Borchgrevink landed from one of these vessels for the first time on
southern continental land near Cape Adare.
In 1898 three expeditions started south. The first, a Belgian
undertaking on board the Belgica, explored the coast to the north of
Graham Land, and brought back valuable collections; the second,
from Germany on the Valdivia, re-discovered Bouvet Island, whose
position had long been lost; the third, from England, under
Borchgrevink on the Southern Cross, landed the first party to winter
in the Antarctic, reached Mount Terror, and sailed along the Great
Ice Barrier, reaching latitude 78° S. In 1901 the problem was
attacked for the first time by means of land-exploration; a well-
equipped expedition leaving England in that year under Captain R. F.
Scott voyaged along the ice-barrier, and found and named King
Edward Land, first seen by Ross. Scott then proved Mount Erebus
and Mount Terror to be on an island, and wintered on shore. In the
following southern summer Scott, with Wilson and Shackleton,
pushed southward and reached the latitude of 82° 17´, where the
Great Ice Barrier reaches the foot of the lofty plateau on which the
south pole is placed. Other parties traversed the ice-barrier in
various directions, and much valuable scientific work was done in
geology, biology, meteorology, magnetism, and glaciation. While
Scott was in the Antarctic to the south of New Zealand, a German
expedition, under E. von Drygalski, on board the Gauss, was working
to the west of him, and had discovered and named Kaiser Wilhelm
II. Land. Two private expeditions were also in the Antarctic at the
same time, and the large number of synchronous meteorological and
magnetic observations thus taken formed a valuable contribution to
the knowledge of the southern continent. In 1903 a voyage was
made by W. S. Bruce on the Scotia, which is important for the
exploration of an entirely unknown sea lying between the tracks of
Weddell and of Ross; the latitude of 74° 1´ was reached. Though
the land could not be attained, its existence was proved by
occasional glimpses and by the dredging up of continental rocks, and
the name of Coats Land was given to it. In 1904 J. B. Charcot, a
French scientist, cruised along Graham Land and found a new line of
coast, which he named Loubet Land. Thus between 1902 and 1904
new land had been discovered in all the four quarters of the
Antarctic circle—King Edward Land by Scott, Kaiser Wilhelm Land by
Drygalski, Coats Land by Bruce, and Loubet Land by Charcot.
Lieutenant (afterwards Sir) E. H. Shackleton, who had
accompanied Scott, led an expedition to the south in 1908–9, which
landed at the foot of Mount Erebus. That mountain was ascended by
Professor T. W. E. David, who also, with Dr. D. Mawson, reached the
south magnetic pole in 72° 25´ S., 155° 16´ E. Shackleton himself
led the famous march which brought him to 88° 23´ S., 162° E., a
great advance towards the south pole itself, which might actually
have been attained but for the lack of food. The scientific results of
the expedition were of high value, and revealed the desirability of
prosecuting researches in the same field; and in 1910 Scott led a
second expedition, with a larger scientific staff than had ever been
taken before, the main party of which was landed at Cape Evans,
McMurdo Sound. Of two other parties, one was landed on the west
side of the sound; another, which worked at first from Cape Adare,
was subsequently transferred to Terra Nova Bay, Victoria Land. A
considerable area was thus covered on this part of the Antarctic
coast, while Scott’s march upon the pole was designed to follow
Shackleton’s route. The splendour of success was outshone by the
splendour of disaster: Scott and four companions, having reached
the pole, died bravely on the return journey, overcome by adverse
conditions. The work of the expedition as a whole, taking that of the
other parties into account, was a brilliant scientific triumph.
The honour of first reaching the pole, however, fell to a
Norwegian explorer, Captain Roald Amundsen, who, leading a small
but admirably equipped expedition, succeeded in his endeavour at
the end of 1911, and he and Scott thus left the way open to
research on the Antarctic land-mass unhampered for the future by
the natural desire to reach a certain point upon it. In the same year
expeditions (not specifically concerned with the attainment of that
point) were led south by the German Lieutenant Filchner, whose
immediate goal was Coats Land, in the “Weddell” (or South
American) quadrant, and by Dr. Mawson, whose objective was Adélie
Land, on the opposite flank of the continent, while various projects
are also under the consideration of other voyagers, British and
American. There is room for the work of all these and more—the
Antarctic region is now known as a vast land-area fringed by deep
seas separating it from the other continental masses. Amundsen’s
observations would seem to prove it a single homogeneous mass,
and not to be divided into two, or to consist in part of an
archipelago. It still remains to investigate the nature of any
geological relation between it and the other continents, to study the
extension and physiography of the great mountain ranges which are
known, and their relation to the polar plateau, and to deal with the
many other problems such as are suggested by observations already
made on the climate, the ice conditions, and the distribution of flora
and fauna—notably, in the last connection, the problem of the
resemblances which have been observed between Antarctic and
Arctic forms of life.
Chapter XIV.

THE NINETEENTH CENTURY AND AFTER;


EVOLUTION AND PROGRESS OF
GEOGRAPHICAL SCIENCE

As during a long period in the history of geography it was usual to


limit the connotation of the term, so, when a wider connotation
came to be recognized, there naturally followed the creation of
certain clearly-defined departments of study under distinguishing
titles. The whole structure of geography rests upon two great pillars
—upon exploration and upon measurement. With the main lines of
exploration we have dealt in preceding chapters, and we have
carried that part of our history which deals with precise
measurement down to the close of the eighteenth century and the
institution of the ordnance survey of Great Britain (Chapter X.). The
early part of the sixteenth century witnessed the birth of accurate
land-measurement; the early part of the nineteenth its re-birth as a
function of organized state-administration. The Indian
trigonometrical survey, with which the names of Col. W. Lambton
and afterwards Sir George Everest are associated, was begun in
1800; a famous survey of Switzerland, coupled with the name of
Gen. H. Dufour, was undertaken in 1809, one of Austria-Hungary in
1816, one of France in 1817; what is now the territory of the
German Empire was already fairly represented on local maps when a
general survey was undertaken in 1878. Indeed, all European
countries may be said to be completely surveyed except certain of

You might also like