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

The First Line of Code: Android Programming with Kotlin Lin Guo pdf 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 using Kotlin. It includes a variety of resources and links to other related books, emphasizing the systematic coverage of essential topics in Android and Kotlin programming. The book is designed to be accessible, allowing readers to start from any chapter based on their existing knowledge.

Uploaded by

guestdlucyk8d
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)
20 views

The First Line of Code: Android Programming with Kotlin Lin Guo pdf 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 using Kotlin. It includes a variety of resources and links to other related books, emphasizing the systematic coverage of essential topics in Android and Kotlin programming. The book is designed to be accessible, allowing readers to start from any chapter based on their existing knowledge.

Uploaded by

guestdlucyk8d
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/ 48

The First Line of Code: Android Programming with

Kotlin Lin Guo pdf 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
Discovering Diverse Content Through
Random Scribd Documents
treasure convoy having taken the unconscionable time of eleven
days to crawl forward from Lisbon to Abrantes—a distance of no
more than ninety miles[566].
A third cause of delay was the time spent in waiting for
reinforcements from Lisbon. Eight or nine regiments had landed, or
were expected to arrive within the next few days. It was in every
way desirable to unite them to the army before the campaign should
begin. This was all the more necessary because several corps had to
be deducted from the force which had been used in the Oporto
campaign. Under stringent orders from home, Wellesley had sent
back two infantry battalions and part of two cavalry regiments to
Lisbon, to be embarked for Gibraltar and Sicily[567]. In return he was
to receive a much larger body of troops. But while the deduction was
immediate, the addition took time. Of all the troops which were
expected to reinforce the army, only one battalion caught him up at
Abrantes, while a second and one regiment of Light Dragoons[568]
joined later, but yet in time for Talavera. Thus at the commencement
of the actual campaign the force in the field was, if anything, slightly
less in numbers than that which had been available in May. It was
particularly vexatious that the brigade of veteran light infantry, for
which Wellesley had made a special demand on Castlereagh as early
as April, did not reach Abrantes till long after the army had moved
forward. These three battalions, the nucleus of the famous Light
Division[569], had all gone through the experiences of Moore’s
campaign, and were once more under their old leader Robert
Craufurd. Detained by baffling winds in the Downs, the transports
that bore them only reached Lisbon at various dates between June
28 and July 2, though they had sailed on May 25. Their indefatigable
brigadier hurried them forward with all speed to the front, but in
spite of his exertions, they only came up with the main army after
the day of battle was over. The same was the fate of two batteries of
horse artillery[570]—an arm in which Wellesley was wholly deficient
when he marched into Spain. They arrived late, and were still far to
the rear when the march from Abrantes began.
It thus resulted that although there were over 33,000 British
troops in the Peninsula at the commencement of July 1809, less than
21,000 could be collected for the advance on Plasencia which was
now about to begin. More than 8,000 men lay at Lisbon, or were just
starting from that city, while 4,500 were in hospital[571]. The sick
seemed more numerous than might have been expected at the
season of the year: though the fatigues of the Oporto campaign
accounted for the majority of the invalids, yet Wellesley was of
opinion that a contributory cause might be found in the slack
discipline of certain regiments, where inefficient commanding
officers had neglected sanitary precautions, and allowed their men
to neglect personal cleanliness, or to indulge to excess in wine and
unripe fruit and vegetables. It was his opinion that the number of
men in hospital should never exceed ten per cent. of the total force.
But all through the war he found that this proportion was exceeded.
With the internal condition of many of his regiments Wellesley
was far from satisfied. His tendency to use the plainest, indeed the
harshest, terms concerning the rank and file, is so well known that
we are not surprised to find him writing that ‘the army behave
terribly ill: they are a rabble who cannot bear success any more than
Sir John Moore’s army could bear failure[572].’ He complained most of
all of the recruits sent him from the Irish militia, who were, he said,
capable of every sin, moral or military. Though he was ‘endeavouring
to tame the troops,’ yet there were several regiments in such bad
order that he would gladly have sent them home in disgrace if he
could have spared a man. The main offence, of course, was robbery
of food from the Portuguese peasantry, often accompanied by
violence, and now and then by murder. The number of assistant-
provost-marshals was multiplied, some offenders were caught and
hanged, but marauding could not be suppressed, even while the
troops were receiving full rations in their cantonments at Abrantes.
When they were enduring real privation, in the wilds of Estremadura,
matters grew much worse. Though many regiments were
distinguished for their good behaviour, yet there were always some
whose excesses were a disgrace to the British army. Their
Commander never shrank from telling them so in the most incisive
language; he was always complaining that he could not get a
sufficient number of the criminals flogged or hanged, and that
regimental court-martials were far too lenient in their dealings with
offenders[573].
It was at Abrantes that Wellesley first arranged his army in
divisions, and gave it the organization which, with certain
modifications, it was to maintain during the rest of the war. His six
regiments of cavalry were to form a single division consisting of one
heavy and two light brigades, commanded respectively by Fane,
Cotton, and Anson. The twenty-five battalions of infantry were
distributed into four divisions of unequal strength under Generals
Sherbrooke, Hill, Mackenzie, and A. Campbell. Of these the first was
by far the largest, counting four brigades of two battalions each: the
first (Henry Campbell’s) was formed of the two battalions of Guards,
the second (Cameron’s) of two line regiments, the third and fourth,
under Low and Langwerth, comprised the infantry of the King’s
German Legion. The second and third divisions each consisted of
two brigades of three battalions each[574]. The fourth, and weakest,
showed only five battalions in line. Of artillery there were only thirty
guns, eighteen English and twelve German: all were field-batteries,
as none of the much-desired horse artillery had yet reached the
front[575]. They were all of very light calibre, the heaviest being a
brigade of heavy six-pounders belonging to the German Legion.
On June 28 the army at last moved forward: that day the head
quarters were at Cortiçada, on the Sobreira Formosa. On the
thirtieth Castello Branco, the last Portuguese town, was reached. On
July 3 the leading brigades passed the Elga, the frontier river, and
bivouacked on the same night around Zarza la Mayor, the first place
in Spanish Estremadura. At the same time Sir Robert Wilson’s small
column of 1,500 Portuguese crossed the border a little further north,
and advanced in a direction parallel to that of the main army, so as
to serve as a flank guard for it in the direction of the mountains.
King Joseph meanwhile was in a state of the most profound
ignorance concerning the impending storm. As late as July 9 he
wrote to his brother that the British had not as yet made any
pronounced movement, and that it was quite uncertain whether they
would invade Galicia, or strike at Castile, or remain in the
neighbourhood of Lisbon[576]! On that day the head of the British
army had entered Plasencia, and was only 125 miles from Madrid. It
is impossible to give any better testimonial than this simple fact to
the way in which the insurgents and the guerrillas served the cause
of the allies. Wellesley had been able to march from Oporto to
Abrantes, and from Abrantes to Plasencia, without even a rumour of
his advance reaching Madrid. All that Joseph had learnt was that
there was now an allied force of some sort behind Alcantara, in the
direction of Castello Branco. He took it for granted that they were
Portuguese, but in one dispatch he broaches the theory that there
might be a few English with them—perhaps from having heard a
vague report of the composition of Mackenzie’s division on the
Zezere in May. He therefore wrote in a cheerful tone to the Emperor
that ‘if we have only got to deal with Cuesta and the Portuguese
they will be beaten by the 1st Corps. If they have some English with
them, they can be beaten equally well by the 1st Corps, aided by
troops which I can send across the Tagus via Toledo’ (i.e. the 5,000
or 6,000 men of the Central Reserve which could be spared from
Madrid). ‘I am not in the least disquieted,’ he continued, ‘concerning
the present condition of military affairs in this part of Spain[577].’ In
another epistle to his brother he added that ‘if the English should be
at the back of Cuesta, it would be the happiest chance in the world
for the concluding of the whole war[578].’
It was lucky for the King that he was not induced to try the
experiment of falling upon Wellesley and Cuesta with the 28,000
men of Victor and the Central Reserve. If he had done so, he would
have suffered a frightful disaster and have lost Madrid.
In the end of June and the first days of July Joseph’s main
attention had been drawn off to that part of his front where there
was least danger, so that he was paying comparatively little heed to
the movements of the allies on the lower Tagus. He had been
distracted by a rash and inexplicable movement of the Spanish army
of La Mancha. When General Venegas had heard of the retreat of
Victor from Estremadura, and had been informed that Cuesta was
about to move forward in pursuit of the 1st Corps, he had concluded
that his own troops might also advance. He argued that Sebastiani
and the 4th Corps must beat a retreat, when their right flank was
uncovered by Victor’s evacuation of the valley of the Guadiana. He
was partly justified in his idea, for Joseph had drawn back
Sebastiani’s main body to Madridejos when Victor abandoned
Merida. It was safe therefore to advance from the Despeña Perros
into the southern skirts of La Mancha, as far as Manzanares and the
line of the Guadiana. But to go further forward was dangerous,
unless Venegas was prepared to risk a collision with Sebastiani. This
he was certainly not in a condition to do: his troops had not yet
recovered from the moral effects of the rout of Ciudad Real, and his
brigades were full of new battalions of untried Andalusian reserves.
He should have been cautious, and have refused to move without
concerting his operations with Cuesta: to have had his corps put
hors de combat at the very beginning of the joint campaign of the
allied armies would have been most disastrous.
Nevertheless Venegas came down from the passes of the Sierra
Morena with 18,000 infantry, 3,000 horse, and twenty-six guns, and
proceeded to thrust back Sebastiani’s cavalry screen and to push in
his outposts in front of Madridejos. The French general had in hand
at this moment only two infantry divisions and Milhaud’s dragoons;
his third division and his light cavalry were still absent with Victor, to
whom they had been lent in March for the campaign of Medellin. But
with 13,000 foot and 2,000 horse[579] he ought not to have feared
Venegas, and could have given a good account of him had he
chosen to attack. But having received exaggerated reports of the
strength of the Spanish army, he wrote to the King that he was
beset by nearly 40,000 men and must be reinforced at once, or he
would have to fall back on Madrid[580]. Joseph, fully believing the
news, sent orders to Victor to restore to the 4th Corps the divisions
of Leval and Merlin, and then, doubting whether these troops could
arrive in time, sallied out of Madrid on June 22 with his Guards and
half the division of Dessolles—about 5,500 men.
It was lucky for Venegas that Sebastiani had refused to fight him,
but still more lucky that the news of the King’s approach reached
him promptly. On hearing that Joseph had joined the 4th Corps on
June 25 he was wise enough to turn on his heel and retreat in all
haste towards his lair in the passes of the Sierra Morena. If he had
lingered any longer in the plains he would have been destroyed, for
the King, on the arrival of Leval’s and Merlin’s divisions, would have
fallen upon him at the head of 27,000 men. As it was, Venegas
retired with such promptitude to Santa Cruz de Mudela, at the foot
of the passes, that the French could never catch him. Joseph
pursued him as far as Almagro and El Moral, on the southern edge
of La Mancha, and there stopped short. He had received, on July 2,
a dispatch from Victor to the effect that Cuesta had repaired the
bridge of Almaraz and begun to cross the Tagus, while a body of
10,000 allied troops, presumably Portuguese, had been heard of in
the direction of Plasencia[581]. (This was in reality the whole army of
Wellesley!) Rightly concluding that he had pushed the pursuit of
Venegas too far, the King turned back in haste, left Sebastiani and
the 4th Corps behind the Guadiana, and returned with his reserve to
Toledo, in order to be in a position to support Victor. His excursion to
Almagro had been almost as reckless and wrongheaded as
Venegas’s advance to Madridejos, for he had separated himself from
Victor by a gap of 200 miles, at the moment when the British army
was just appearing on the Marshal’s flank, while Cuesta was in his
front. If the allied generals had concentrated their forces ten days
earlier—a thing that might well have happened but for the vexatious
delays at Abrantes caused by Cuesta’s impracticability—the 1st Corps
might have been attacked at the moment when Joseph lay at the
foot of the Sierra Morena, in a position too remote from Talavera to
allow him to come up in time to succour Victor.
While the King was absent on his expedition in pursuit of Venegas
the most important change in the situation of affairs on the Tagus
was that the Duke of Belluno had drawn back his troops from the
line of the Tagus, where they had been lying since June 19, and had
retired behind the Alberche. His retreat was not caused by any
apprehension as to the appearance of Wellesley on his flank—a fact
which was completely concealed from him—but by sheer want of
provisions. On June 25 he sent to the King to say that his army was
again starved out of its cantonments, and that he had eaten up in a
week the small remnant of food that could be squeezed out of the
country-side between the Tagus and the Tietar, and was forced to
transfer himself to another region. ‘The position,’ he wrote, ‘is
desperate. The 1st Corps is on the eve of dissolution: the men are
dropping down from mere starvation. I have nothing, absolutely
nothing, to give them. They are in a state of despair.... I am forced
to fall back on Talavera, where there are no more resources than
here. We must have prompt succour, but where can it be found? If
your Majesty abandons me in my present wretched situation, I lose
my honour, my military record—everything. I shall not be to blame
for the disaster which menaces my troops, but I shall have to bear
the blame. Tomorrow I shall be at Talavera, waiting your Majesty’s
orders. The enemy [Cuesta] has a pontoon-train: if he wishes to
cross the Tagus he can do so, for the 1st Corps can no longer remain
opposite him. Never was there a more distressing situation than
ours[582].’
On June 26, therefore, Victor transferred himself to Talavera, and
adopted a position behind the Alberche, after burning the materials
of the late pontoon bridge at Almaraz, which he had taken up and
stored in case they might again be needed. His movement was a
lucky one for himself, as it took him further away from Wellesley’s
army, which was just about to start from Abrantes with the object of
turning his flank. It puzzled Cuesta, who sought for some other
explanation of his departure than mere starvation, and was very
cautious in taking advantage of it. However, on the day after the
French had withdrawn, he pushed troops across the Tagus, and
prepared to construct another bridge at Almaraz to replace that
which the French had destroyed. His cavalry pushed out to
Navalmoral and Oropesa, and further to the east he passed some
detachments of infantry across the bridge of Arzobispo, which Victor
—most unaccountably—had left intact. Fortunately he did no more,
and refrained from advancing against Talavera, a step which from his
earlier record we should judge that he might well have taken into
consideration.
On the part of the allies things were now in a state of suspense
from which they were not to stir for a fortnight. Cuesta was waiting
for Wellesley, Wellesley was pushing forward from Zarza la Mayor to
join Cuesta. Venegas was recovering at Santa Cruz de Mudela from
the fatigues of his fruitless expedition into La Mancha.
But on the French side matters suffered a sudden change in the
last days of July—the hand of the Emperor was stretched out from
the banks of the Danube to alter the general dispositions of the
army of Spain. On June 12 he had dictated at Schönbrunn a new
plan of campaign, based on information which was already many
weeks old when it reached him. At this date the Emperor was barely
aware that Soult was being pressed by Wellesley in Northern
Portugal. He had no detailed knowledge of what was taking place in
Galicia or the Asturias, and was profoundly ignorant of the intrigues
at Oporto which afterwards roused his indignation. But he was
convinced that the English army was the one hostile force in Spain
which ought to engage the attention of his lieutenants. Acting on
this belief he issued an order that the 2nd, 5th, and 6th Corps—
those of Soult, Mortier, and Ney—were to be united into a single
army, and to be told off to the task of evicting Wellesley from
Portugal. They were to put aside for the present all such subsidiary
enterprises as the subjection of Galicia and the Asturias, and to
devote themselves solely to ‘beating, hunting down, and casting into
the sea the British army. If the three Corps join in good time the
enemy ought to be crushed, and then the Spanish war will come to
an end. But the troops must be moved in masses and not march in
small detachments.... Putting aside all personal considerations, I give
the command of the united army to the Duke of Dalmatia, as the
senior marshal. His three Corps ought to amount to something
between 50,000 and 60,000 men[583].’
This dispatch reached King Joseph at El Moral in La Mancha on
July 1, and Soult at Zamora on July 2. It had been drawn up in view
of events that were taking place about May 15. It presupposed that
the British army was still in Northern Portugal, in close touch with
Soult, and that Victor was in Estremadura[584]. As a matter of fact
Soult was on this day leading his dilapidated corps down the Esla, at
the end of his retreat from Galicia. Ney, furious at the way in which
his colleague had deserted him, had descended to Astorga three
days before. Mortier was at Valladolid, just about to march for
Villacastin and Madrid, for the King had determined to draw him
down to aid in the defence of the capital. Finally, Cuesta, instead of
lying in the Sierra Morena, as he was when Napoleon drew up his
orders, was now on the Tagus, while Wellesley was no longer in
touch with Soult on the Douro, but preparing to fall upon Victor in
New Castile. The whole situation was so changed that the
commentary which the Emperor appended to his orders was
hopelessly out of date—as was always bound to be the case so long
as he persisted in endeavouring to direct the course of affairs in
Spain from the suburbs of Vienna.
Soult was overjoyed at receiving the splendid charge which the
Emperor’s decree put into his hands, though he must have felt
secret qualms at the idea that ere long some account of his doings
at Oporto must reach the imperial head quarters and provoke his
master’s wrath. There was a bad quarter of an hour to come[585]. But
meanwhile he was given a formidable army, and might hope to
retrieve the laurels that he had lost in Portugal, being now in a
position to attack the British with an overwhelming superiority of
numbers. It must have been specially delightful to him to find that
Ney had been put under his orders, so that he would be able to
meet his angry colleague in the character of a superior officer
dealing with an insubordinate lieutenant.
Soult’s first action, on finding himself placed in command of the
whole of the French forces in North-western Spain, was to issue
orders to Mortier to march on Salamanca, and to Ney to bring the
6th Corps down to Benavente. These dispositions clearly indicate an
intention of falling upon Ciudad Rodrigo and Almeida, and assailing
Northern Portugal—the plan which the Duke of Dalmatia had
broached to the King in his letter from Puebla de Senabria on June
25, before he had received the news that the 5th and 6th Corps had
been added to his command.
It is clear that on July 2 Soult had no knowledge of Wellesley’s
movements, and thought that the British army was quite as likely to
be aiming at Salamanca as at Madrid. It is also evident that he was
aware that he would be unable to move for some weeks. Till the 2nd
Corps should have received the clothing, munitions, and artillery
which had been promised it, it could not possibly take the field for
the invasion of Portugal.
Soult, therefore, was obliged to wait till his stores should be
replenished, and till the two corps from Astorga and Valladolid
should concentrate on his flanks. It was while he was remaining
perforce in this posture of expectation that the news of the real
condition of affairs in New Castile was at last brought to him.
SECTION XVI: CHAPTER III
WELLESLEY AND CUESTA: THE INTERVIEW AT
MIRABETE

It was not till the third day of July that Wellesley had been able to
cross the Spanish border. Since Victor had assumed his new position
to the north of the Tagus as early as the nineteenth of the preceding
month, there was a perilous fortnight during which Cuesta and his
army were left alone to face the French. All through this time of
waiting, the British Commander-in-chief was haunted by the dread
that the old Captain-General might repeat his earlier errors, and
once more—as at Rio Seco and Medellin—court a pitched battle.
Wellesley had done his best to urge caution, by letters written not
only to Cuesta himself, but to his Chief-of-the-staff O’Donoju and to
Colonel Roche, who had now replaced Bourke as British
representative at the head quarters of the Army of Estremadura.
Fortunately they were not needed: the Spanish General was for once
cautious: he followed Victor at a respectful distance, and when he
had reached the Tagus and repaired the bridge of Almaraz, held
back his army to the southern bank and only pushed a few small
detachments beyond the stream to search for the enemy. Since the
French had withdrawn to Talavera on June 26 there was no collision.
The cavalry of the 1st Corps were discovered upon the upper Tietar
and the Alberche, but they preserved a defensive attitude, and the
Spaniards did not provoke them by any rash attempt to drive them
back upon their main body. All remained quiet, as Wellesley had
rather desired than expected.
Cuesta’s strategical position, therefore, was perfectly secure, since
he kept his main body to the south of the river, and showed no
desire to meddle with Victor before the arrival of the British. At this
moment military affairs were not the only things that were engaging
the attention of the old Captain-General. He was watching with
considerable anxiety the course of events at Seville, where he was
aware that he had many enemies. Ever since his high-handed action
against the deputies of Leon in the preceding autumn, he knew that
the Central Junta, and especially its Liberal wing, viewed him with
suspicion and dislike. It was with great reluctance that they had
placed him in command of the Estremaduran army, and if he had not
been popular with the Conservative and clerical party and with some
of the military cliques, he would not have retained his post for long.
At this moment there were many intrigues stirring in Andalusia, and
if some of them were directed against the Junta, others had no
other end than the changing of the commanders of the various
armies. While the Junta were debating about forms of government,
and especially about the summoning of a national Cortes in the
autumn, there were a number of officers of damaged reputation
whose main object was to recover the military rank of which they
had been deprived after misfortunes in the field. Infantado, who
thought that it was absurd that he should have been disgraced after
Ucles, while Cuesta had been rewarded after Medellin, was at the
head of one party of intriguers, which included Francisco Palafox and
the Conde de Montijo, and had secured the aid of Colonel Doyle, late
British agent in Aragon and Catalonia, an officer who showed a
lamentable readiness to throw himself into the intestine quarrels of
the Spanish factions[586]. Their actions went to the very edge of high
treason, for Montijo stirred up a riot at Granada on April 16, attacked
the provincial authorities, and almost succeeded in carrying out a
pronunciamiento which must have led to civil war. The Junta did no
more than banish him to San Lucar, from which place he continued
his plots with Infantado, in spite of the warning that he had
received.
In Seville, faction if not so openly displayed was equally violent.
There was, as we have already said, a large section of the Junta
whose dearest wish would have been to displace Cuesta: it was they
who had obtained the nomination of Venegas to take charge of the
troops in La Mancha, merely because he was known to be an enemy
of the elder general. Yet since the two armies would have to co-
operate in any attempt to recover Madrid, it was clearly inexpedient
that their commanders should be at enmity. Some of the politicians
at Seville were set on giving high command to the Duke of
Albuquerque, an energetic and ambitious officer, but one gifted with
the talent of quarrelling with every superior under whom he served:
he was now bickering with Cuesta just as in March he had bickered
with Cartaojal. The Duke was a great admirer of all things English,
and a personal friend of Frere, the British minister. The latter did his
best to support his pretensions, often expressing in official
correspondence with the Junta a desire that Albuquerque might be
given an independent corps, and entrusted with the charge of the
movement that was to be concerted in conjunction with Wellesley’s
army.
But it was not so much Albuquerque as Wellesley himself that
Cuesta dreaded as a possible successor. For Frere was possessed
with the notion that the time had now arrived at which it would be
possible to press for the appointment of a single Commander-in-
chief of all the Spanish armies. The obvious person to fill this post
was the victor of Vimiero and Oporto, if only Spanish pride would
consent to the appointment of a foreigner. Frere had sufficient sense
to refrain from openly publishing his idea. But he was continually
ventilating it to his private friends in the Junta, in season and out of
season. There can be no doubt that both from the military and the
political point of view the results of Wellesley’s exaltation to the
position of Generalissimo would have been excellent. If he had
controlled the whole of the Spanish armies in the summer of 1809,
the course of affairs in the Peninsula would have taken a very
different turn, and the campaign of Talavera would not have been
wrecked by the hopeless want of co-operation between the allied
armies. But it was not yet the time to press for the appointment:
great as Wellesley’s reputation already was, when compared with
that of any Spanish general, it was still not so splendid or so
commanding as to compel assent to his promotion[587]. Legitimate
national pride stood in the way, and even after Espinosa, and Tudela,
and Medellin the Spaniards could not believe that it was necessary
for them to entrust the whole responsibility for the defence of their
country to the foreigner. Only a few of the politicians of Seville
showed any liking for the project. Wellesley himself would have
desired nothing so much as this appointment, but being wiser and
less hopeful than Frere, he thought it useless to press the point.
When the sanguine diplomat wrote to him, early in June, to detail
his attempts to bring home the advisability of the project to his
Spanish friends, the general’s reply was cautious in the extreme. ‘I
am much flattered,’ he said, ‘by the notion entertained by some of
the persons in authority at Seville, of appointing me to the command
of the Spanish armies. I have received no instruction from
Government upon that subject: but I believe that it was considered
an object of great importance in England that the Commander-in-
chief of the British troops should have that situation. But it is one
more likely to be attained by refraining from pressing it, and leaving
it to the Spanish themselves to discover the expediency of the
arrangement, than by any suggestion on our parts.’ He concluded by
informing Frere that he could not conceive that his insinuation was
likely to have any effect, and that the opinion of the British Ministry
was probably correct—viz. that at present national jealousy made
the project hopeless[588].
Now it was impossible that Frere’s well-meaning but mistaken
endeavours should escape the notice of Cuesta’s friends in Seville.
The British Minister had spoken to so many politicians on the
subject, that we cannot doubt that his colloquies were promptly
reported to the Captain-General of Estremadura. This fact goes far
to explain Cuesta’s surly and impracticable behaviour towards
Wellesley during the Talavera campaign. He disliked his destined
colleague not only because he was a foreigner, and because he
showed himself strong-willed and outspoken during their
intercourse, but because he believed that the Englishman was
intriguing behind his back to obtain the post of Generalissimo. This
belief made him determined to assert his independence on the most
trifling matters, loth to fall in with even the most reasonable plans,
and suspicious that every proposal made to him concealed some
trap. He attributed to Wellesley the design of getting rid of him, and
was naturally determined to do nothing to forward it.
The English officers who studied Cuesta’s conduct from the
outside, during the Talavera campaign, attributed his irrational
movements and his hopeless impracticability to a mere mixture of
pride, stupidity, and obstinacy. They were wrong; the dominant
impulse was resentment, jealousy, and suspicion—a combination far
more deadly in its results than the other. He awaited the approach of
Wellesley with a predisposition to quarrel and a well-developed
personal enmity, whose existence the British general had not yet
realized.
We have dealt in the last chapter with the strength and
organization of the British army at the moment when Wellesley
crossed the frontier on July 3. It remains to speak of the two
Spanish armies which were to take part in the campaign. We have
already seen that Cuesta’s host had been reinforced after Medellin
with a new brigade of Granadan levies, and a whole division taken
from the army of La Mancha[589]. Since that date he had received
large drafts both of infantry and cavalry from Andalusia. Six more
regiments of horse had reached him, besides reinforcements for his
old corps. All were now strong in numbers, and averaged between
400 and 500 sabres, so that by the middle of June he had fully 7,000
mounted men under his orders. Eight or nine additional regiments of
infantry had also come to hand since April—some of them new
Andalusian levies, others old corps whose cadres had been filled up
since the disaster of Ucles. His infantry counted about 35,000
bayonets, divided into five divisions and a ‘vanguard’: the latter
under Zayas was about 4,000 strong, each of the others exceeded
5,000. The cavalry formed two divisions, under Henestrosa and
Albuquerque, one composed of seven, one of six regiments. There
were thirty guns—some of heavy calibre, nine-and twelve-pounders
—with about 800 artillerymen. The whole army, inclusive of sick and
detached, amounted to 42,000 men, of whom perhaps 36,000 were
efficients present with the colours[590].
The second Spanish army, that of La Mancha under Venegas, was
much weaker, having furnished heavy detachments to reinforce
Cuesta before it took the field in June. Its base was the old ‘Army of
the Centre,’ which had been commanded by Castaños and Infantado.
Some twenty battalions that had seen service in the campaign of
Tudela were still in its ranks: they had been recruited up to an
average of 500 or 600 bayonets. The rest of the force was composed
of new Andalusian regiments, raised in the winter and spring, some
of which had taken part in the rout of Ciudad Real under Cartaojal,
while others had never before entered the field. The gross total of
the army on June 16 was 26,298 men, of whom 3,383 were cavalry.
Deducting the sick in hospital, Venegas could dispose of some
23,000 sabres and bayonets, distributed into five divisions. The
horsemen in this army were not formed into separate brigades, but
allotted as divisional cavalry to the infantry units. There was little to
choose, in point of efficiency, between the Estremaduran army and
that of La Mancha; both contained too many raw troops, and in
both, as was soon to be proved, the bulk of the cavalry was still as
untrustworthy as it had shown itself in previous engagements.
The Spaniards therefore could put into the field for the campaign
of July on the Tagus some 60,000 men. But the fatal want of unity in
command was to prevent them from co-ordinating their movements
and acting as integral parts of a single army guided by a single will.
Venegas was to a certain degree supposed to be under Cuesta’s
authority, but as he was continually receiving orders directly from
the Junta, and was treated by them as an independent commander,
he practically was enabled to do much as he pleased. Being a
personal enemy of Cuesta, he had every inducement to play his own
game, and did not scruple to do so at the most important crisis of
the campaign,—covering his disregard of the directions of his senior
by the easy pretext of a desire to execute those of the central
government.
On July 15, the day when his share in the campaign commenced,
the head quarters of Venegas were at Santa Cruz de Mudela, just
outside the northern exit of the Despeña Perros. His outposts lay in
front, at El Moral, Valdepeñas, and Villanueva de los Infantes. He
was divided by a considerable distance—some twenty-five miles—
from the advanced cavalry of Sebastiani’s corps, whose nearest
detachment was placed at Villaharta, where the high-road to Madrid
crosses the river Giguela.
Meanwhile we must return to Wellesley, who having crossed the
frontier on July 3, was now moving forward by short marches to
Plasencia. On the fourth the head quarters were at Zarza la Mayor,
on the sixth at Coria, on the seventh at Galisteo; on the eighth
Plasencia was reached, and the general halted the army, while he
should ride over to Almaraz and confer in person with Cuesta on the
details of their plan of campaign. In the valley of the Alagon, where
the country was almost untouched by the hand of war, provisions
were obtainable in some quantity, but every Spanish informant
agreed that when the troops dropped down to the Tagus they would
find the land completely devastated. Wellesley was therefore most
anxious to organize a great dépôt of food before moving on: the
local authorities professed great readiness to supply him, and he
contracted with the Alcaldes of the fertile Vera de Plasencia for
250,000 rations of flour to be delivered during the next ten days[591].
Lozano de Torres, the Spanish commissary-general sent by the Junta
to the British head quarters, promised his aid in collecting the food,
but even before Wellesley departed to visit Cuesta, he had begun to
conceive doubts whether supplies would be easily procurable. The
difficulty was want of transport—the army had marched from
Portugal with a light equipment, and had no carts to spare for
scouring the country-side in search of flour. The General had relied
on the assurances sent him from Seville to the effect that he would
easily be able to find local transport in the intact regions about Coria
and Plasencia: but he was disappointed: very few carts could be
secured, and the store of food in the possession of the army seemed
to shrink rather than to increase during every day that the army
remained in the valley of the Alagon, though the region was fruitful
and undevastated. It is certain that the British commissaries had not
yet mastered the art of gathering in provisions from the country-
side, and that the Spanish local authorities could not be made to
understand the necessity for punctuality and dispatch in the delivery
of the promised supplies.
On July 10 Wellesley started off with the head-quarters staff to
visit Cuesta, at his camp beyond the bridge of Almaraz, there to
concert the details of their joint advance. Owing to an error made by
his guides he arrived after dusk at the hamlet below the Puerto de
Mirabete, around which the main body of the Army of Estremadura
was encamped. The Captain-General had drawn out his troops in the
afternoon for the inspection of the British commander. When at last
he appeared they had been four hours under arms in momentary
expectation of the arrival of their distinguished visitor, and Cuesta
himself, though still lame from the effect of his bruises at Medellin,
had sat on horseback at their head during the greater part of that
time.
Two admirable accounts of the review of the Estremaduran host
in the darkness were written by members of Wellesley’s staff. It is
well worth while to quote one of them[592], for the narrative
expresses with perfect clearness the effect which the sight of the
Spanish troops made upon their allies:—
‘Our arrival at the camp was announced by a general discharge of
artillery, upon which an immense number of torches were made to
blaze up, and we passed the entire Spanish line in review by their
light. The effect produced by these arrangements was one of no
ordinary character. The torches, held aloft at moderate intervals,
threw a red and wavering light over the whole scene, permitting at
the same time its minuter parts to be here and there cast into the
shade, while the grim and swarthy visages of the soldiers, their
bright arms and dark uniforms, appeared peculiarly picturesque as
often as the flashes fell upon them. Nor was Cuesta himself an
object to be passed by without notice: the old man preceded us, not
so much sitting upon his horse as held upon it by two pages, at the
imminent risk of being overthrown whenever a cannon was
discharged, or a torch flamed out with peculiar brightness. His
physical debility was so observable as clearly to mark his unfitness
for the situation which he held. As to his mental powers, he gave us
little opportunity of judging, inasmuch as he scarcely uttered five
words during the continuance of our visit: but his corporal infirmities
were ever at absolute variance with all a general’s duties.
‘In this way we passed by about 6,000 cavalry drawn up in rank
entire, and not less than twenty battalions of infantry, each of 700 to
800 bayonets. They were all, without exception, remarkably fine
men. Some indeed were very young—too young for service—
particularly among the recruits who had lately joined. But to take
them all in all, it would not have been easy to find a stouter or more
hardy looking body of soldiers in any European service. Of their
appointments it was not possible to speak in the same terms of
commendation. There were battalions whose arms, accoutrements,
and even clothing might be pronounced respectable[593]: but in
general they were deficient, particularly in shoes. It was easy to
perceive, from the attitude in which they stood, and the manner in
which they handled their arms, that little or no discipline prevailed
among them: they could not but be regarded as raw levies.
Speaking of them in the aggregate they were little better than bold
peasantry, armed partially like soldiers, but completely unacquainted
with a soldier’s duty. This remark applied to the cavalry as much as
to the infantry. Many of the horses were good, but the riders
manifestly knew nothing of movement or of discipline: and they
were on this account, as also on that of miserable equipment, quite
unfit for service. The generals appeared to have been selected by
one rule alone—that of seniority. They were almost all old men, and,
except O’Donoju and Zayas, evidently incapable of bearing the
fatigues or surmounting the difficulties of a campaign. It was not so
with the colonels and battalion commanders, who appeared to be
young and active, and some of whom were, we had reason to
believe, learning to become skilful officers.... Cuesta seemed
particularly unwilling that any of his generals should hold any serious
conversation with us. It is true that he presented them one by one
to Sir Arthur, but no words were exchanged on the occasion, and
each retired after he had made his bow.’ Albuquerque, of whom the
Captain-General was particularly jealous, had been relegated with
his division to Arzobispo, and did not appear on the scene.
The all-important plan of campaign was settled at a long
conference—it lasted for four hours—on the morning of the following
day. According to all accounts the scene at the interview must have
been curious. Cuesta could not, or would not, speak French:
Wellesley was not yet able to express himself fluently in Spanish.
Accordingly, O’Donoju, the chief of the staff of the Army of
Estremadura, acted as interpreter between them, rendering
Wellesley’s views into Spanish and Cuesta’s into English. The greater
part of the discussion consisted in the bringing forward of plans by
the British commander and their rejection by the Captain-General.
Cuesta was full of suspicion, and saw a trap in every proposal that
was made to him: he imagined that Wellesley’s main object was to
edge him out of the supreme command. He was almost silent
throughout the interview, only opening his lips to give emphatic
negatives, for which O’Donoju proceeded to find ingenious and
elaborate explanations.
It was not the principles on which the campaign was to be
conducted, but the details of the distribution of the troops on which
the trouble arose. The enemy’s position and force was fairly well
known to both generals, except in one all-important particular. They
were aware that Victor lay behind the Alberche with not much more
than 22,000 men, that Sebastiani was at Madridejos with a
somewhat smaller force[594], and that King Joseph with his central
reserve, which they over-estimated at 12,000 men, was able at any
moment to join the 1st Corps. Hence they expected to find some
34,000 French troops at Talavera, and rightly considered that with
the 55,000 men of their two armies they ought to give a good
account of them. Sebastiani, as they supposed, might be left out of
the game, for occupation for him would be found by the army of La
Mancha, which was to be told off for this purpose and directed to
cling to the skirts of the 4th Corps and never to lose sight of it. As
Venegas would have, according to their calculations, nearly double
the numbers of Sebastiani, he would have no difficulty in keeping
him in check.
But it was not only on the French troops in New Castile that
watch had to be kept. It was necessary to take into account the
enemy beyond the mountains, in the valley of the Douro. The allied
generals were aware that Mortier and Soult must both be
considered. The former they knew to be at Valladolid, and they had
learnt that King Joseph was proposing to bring him down towards
Madrid—as was indeed the fact. Accordingly they expected that he
might turn up in a few days somewhere in the direction of Avila.
Soult they knew to be at Zamora, and from the dispatches captured
with General Franceschi ten days before, they had a good
knowledge of his force and intentions. A study of these documents
led them to conclude that he could not move for many weeks, owing
to the dilapidated state of his corps—which he had painted in the
most moving terms in his letters to King Joseph[595]. They also
gathered that if he moved at all, he would be inclined to threaten
Northern Portugal or Ciudad Rodrigo: in the dispatches captured
with Franceschi he had named Braganza as a point at which he
might strike. Accordingly they opined that he need not be taken very
seriously into consideration, especially as he was wholly destitute of
artillery[596]. Yet he might be drawn into the field by the news that
Madrid was in danger. If he were induced to bring help to the King,
he would almost certainly work by making a diversion against the
communications of the British army, and not by directly joining
himself to Joseph’s army by the long and circuitous march from
Zamora to Madrid. To carry out such a diversion he would be obliged
to cross the lofty Sierra de Francia by one of the passes which lead
from the Salamanca region into the valley of the Alagon—perhaps by
the defile of Perales, but much more probably by the better known
and more practicable pass of Baños. Wellesley took the possibility of
this movement into serious consideration, but did not think that it
would be likely to cause him much danger if it should occur, for he
believed that Soult would bring with him no more than the 15,000 or
18,000 men of his own 2nd Corps. That he would appear not with
such a small force, but with Ney and Mortier in his wake, leading an
army of 50,000 bayonets, did not enter into the mind of the British
commander. Mortier was thought to be moving in the direction of
Avila: Ney was believed to be contending with the Galician
insurgents in the remote regions about Lugo and Corunna. The news
of his arrival at Astorga had not yet reached the allied camps, and
he was neglected as a factor in the situation. Wellesley and Cuesta
had no conception that any force save that of Soult was likely to
menace their northern flank and their line of communications when
they committed themselves to their advance on Madrid. To provide
against a possible movement of the 2nd Corps into the valley of the
Tagus, therefore, all that was necessary was to hold the defiles of
Perales and Baños. The former had already been seen to, for even
before the meeting of Wellesley and Cuesta, Carlos d’España had
blocked it with two or three battalions drawn from the garrison of
Ciudad Rodrigo. For the latter Wellesley hoped that Cuesta would
provide a sufficient garrison[597]. The old Captain-General promised
to do so, but only sent 600 men under the Marquis Del Reino, a
wholly inadequate detachment[598].
Wellesley’s first proposal to his Spanish colleague was that the
main bodies of both armies should advance against Victor, while a
detachment of 10,000 men should move out to the left, in the
direction of Avila, to look for Mortier, if he were to be found in that
direction, and if not to turn the enemy’s right and threaten Madrid.
He hoped that Venegas and the army of La Mancha might at the
same time move forward against Sebastiani, and keep him so fully
employed that he would not be able to spare a man to aid Victor and
King Joseph.
Cuesta at once refused to make any detachment in the direction
of Avila from his own army, and suggested that Wellesley should find
the 10,000 men required for this diversion. The English general
objected that it would take exactly half his force, and that he could
not split up such a small unit, while the Spaniards could easily spare
such a number of troops from their total of 36,000 men. This
argument failed to move Cuesta, and the project was dropped,
Wellesley thinking that it was not strictly necessary, though very
advisable[599].
The only flanking force which was finally set aside for operations
on the left wing, for the observation of the French about Avila and
the feint at Madrid, consisted of Sir Robert Wilson’s 1,500
Portuguese, and a corresponding body of two battalions and one
squadron from the Spanish army[600]—about 3,500 men in all. It
played a part of some little importance in the campaign, but it is
hard to see that it would have exercised any dominant influence
even if it had been raised to the full strength that Wellesley had
desired. Mortier, as a matter of fact, was not near Avila, and so the
10,000 men sent in this direction would not have served the end
that the British general expected. The 5th Corps had been called off
by Soult, contrary to the wishes of the King, and no body of troops
was needed to contain it, on this part of the theatre of war. It was
ultimately to appear at a very different point, where no provision had
been made for its reception.
Far more important were the arrangements which Wellesley and
Cuesta made for the diversion on their other flank. It was from the
miscarriage of this operation, owing to the wilful disobedience of the
officer charged with it, that the failure of the whole campaign was to
come about. They agreed that Venegas with the 23,000 men of the
army of La Mancha, was to move up the high-road from his position
at Santa Cruz de Mudela, and drive Sebastiani before him. Having
pushed back the 4th Corps to the Tagus, Venegas was then to
endeavour to force the passage of that river either at Aranjuez or at
Fuentedueñas, and to threaten Madrid. It was calculated that
Sebastiani would be forced to keep between him and the capital,
and would be unable to spare a man to reinforce Victor and King
Joseph. Thus Wellesley and Cuesta with 56,000 men would close on
the King and the Marshal, who could not have more than 35,000,
and (as it was hoped) defeat them or at least manœuvre them out
of Madrid. A glance at the map will show one peculiarity of this plan:
it would have been more natural to bid Venegas march by the bridge
of Toledo rather than by those of Aranjuez and Fuentedueñas; to use
the latter he would have to move towards his right, and to separate
himself by a long gap from the main army of the allies. At Toledo he
would be within thirty-five miles of them—at Aranjuez seventy, at
Fuentedueñas 100 miles would lie between him and the troops of
Wellesley and Cuesta. It would appear that the two generals at their
colloquy came to the conclusion that by ordering Venegas to use the
eastern passages of the Tagus they would compel Sebastiani to
remove eastward also, so that he would be out of supporting
distance of Victor. They recognized the bare possibility that
Sebastiani might refuse to devote himself to the task of holding back
the army of La Mancha, might leave Madrid to its fate, and then
hurry off to join the King and the 1st Corps in an assault on the main
Anglo-Spanish army. In this case they settled that Venegas should
march on the capital and seize it, a move which (as they supposed)
would force Joseph to turn back or to re-divide his army[601]. But it is
clear that they did not expect to have to fight Victor, the King, and
Sebastiani combined, as they were ultimately forced to do at
Talavera on July 28. They supposed that Venegas would find
occupation for the 4th Corps, and that they might count on finding
only the 1st Corps and Joseph’s Madrid reserves in front of them.
When armies are working in a joint operation from separate bases
it is all-important that they should time their movements with the
nicest exactitude. This Wellesley and Cuesta attempted to secure, by
sending to Venegas an elaborate time-table. He was ordered to be at
Madridejos on July 19, at Tembleque on the twentieth, at Santa Cruz
de la Zarza on the twenty-first, and at the bridge of Fuentedueñas
on the twenty-second or twenty-third. All this was on the supposition
that Sebastiani would have about 12,000 men and would give
ground whenever pressed. If he turned out by some unlikely chance
—presumably by having rallied the King’s reserves—to be much
stronger, Venegas was to manœuvre in the direction of Tarancon, to
avoid a general action, and if necessary to retreat towards the
Passes from which he had started. It would be rather an advantage
than otherwise if (contrary to all probability) the French had
concentrated their main force against the army of La Mancha, for
this would leave Victor helpless in front of the united hosts of
Wellesley and Cuesta, which would outnumber him by two to one.
SPANISH COINS OF THE PERIOD OF THE PENINSULAR WAR

What the allied generals never expected was that Venegas would
let Sebastiani slip away from his front, without any attempt to hold
him, and would then (instead of marching on Madrid) waste the
critical days of the campaign (July 24-29) in miserable delays
between Toledo and Aranjuez, when there was absolutely no French
field-force between him and Madrid, nor any hostile troops whatever
in his neighbourhood save a weak division of 3,000 men in garrison
at Toledo. The failure of the Talavera campaign is due even more to
this wretched indecision and disobedience to orders on the part of
Venegas than to the eccentricities and errors of Cuesta. If the army
of La Mancha had kept Sebastiani in check, and refused to allow him
to abscond, there would have been no battles on the Alberche on
July 27-28, for the French would never have dared to face the
Anglo-Spaniards of the main host without the assistance of the 4th
Corps.
But to return to the joint plan of Wellesley and Cuesta: on July
23, the day on which Venegas was to reach Fuentedueñas (or
Aranjuez) the 56,000 men of the grand army were to be assailing
Victor behind the Alberche. The British were to cross the Tietar at
Bazagona on the eighteenth and follow the high-road Navalmoral-
Oropesa. The Estremadurans, passing the Tagus at Almaraz and
Arzobispo, were to move by the parallel route along the river bank
by La Calzada and Calera, which is only five or six miles distant from
the great chaussée. Thus the two armies would be in close touch
with each other, and would not be caught apart by the enemy. On
reaching Talavera they were to force the fords of the Alberche and
fall upon Victor in his cantonments behind that stream. Sir Robert
Wilson and the 3,500 men of his mixed Spanish and Portuguese
detachment were to move up as the flank-guard of the allied host,
and to push by the head waters of the Tietar for Escalona on the
side-road to Madrid[602].
Criticisms of the most acrimonious kind have been brought to
bear on this plan by English, French, and Spanish writers. Many of
them are undeserved; in particular the tritest objection of all, made
ex post facto by those who only look at the actual course of the
campaign, that Wellesley was exposing his communications to the
united forces of Soult, Ney, and Mortier. There was on July 10, when
Cuesta and Wellesley met, no reason whatever for apprehending the
contingency of the march of the three marshals upon Plasencia.
Soult, as his own letters of June 25 bore witness, was not in a
condition to move—he had not a single piece of artillery, and his
troops were in dire need of rest and re-equipment. Ney was believed
to be at Corunna or Lugo—Soult’s intercepted dispatches spoke of
the 6th Corps as being destined to remain behind in Galicia, and he
(as the allied generals supposed) ought best to have known what his
colleague was about to do. How could they have guessed that, in
wrath at his desertion by the Duke of Dalmatia, Ney would evacuate
the whole kingdom, abandon fortresses like Ferrol and Corunna, and
march for Astorga? Without Ney’s corps to aid him, Soult could not
possibly have marched on Plasencia—to have done so with the 2nd
Corps alone would have exposed him to being beset by Wellesley on
one side and by Beresford on the other. As to Mortier and the 5th
Corps, Cuesta and Wellesley undervalued their strength, being
unaware that Kellermann had sent back from the Asturias the
division that had been lent him for his expedition to Oviedo. They
thought that the Duke of Treviso’s force was more like 7,000 than
17,000 bayonets, and—such as it was—they had the best of reasons
for believing that it was more likely to march on Madrid by Avila than
to join Soult, for they had before them an intercepted dispatch from
the King, bidding Mortier to move down to Villacastin in order to be
in supporting distance of the capital and the 1st Corps.
On the whole, therefore, the two generals must be excused for
not foreseeing the descent of 50,000 men upon their
communications, which took place three weeks after their meeting
at the bridge of Almaraz: the data in their possession on July 10
made it appear most improbable.
A much more valid criticism is that which blames the method of
co-operation with Venegas which was employed. ‘Double external
lines of operations’ against an enemy placed in a central position are
notoriously perilous, and the particular movement on Fuentedueñas,
which the army of La Mancha was ordered to execute, was one
which took it as far as possible from Wellesley’s and Cuesta’s main
body. Yet it may be urged in their defence that, if they had drawn in

You might also like