0% found this document useful (0 votes)
11 views83 pages

Android Programming In Java Starting With An App 3rd Edition James download

The document is an overview of the book 'Android Programming in Java: Starting with an App, 3rd Edition' by Mike James, which provides a comprehensive introduction to Android programming using Android Studio. It emphasizes understanding the principles behind Android development, particularly focusing on creating user interfaces and the lifecycle of applications. The book is designed for those with some programming experience, aiming to equip readers with the necessary skills to build simple Android apps.

Uploaded by

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

Android Programming In Java Starting With An App 3rd Edition James download

The document is an overview of the book 'Android Programming in Java: Starting with an App, 3rd Edition' by Mike James, which provides a comprehensive introduction to Android programming using Android Studio. It emphasizes understanding the principles behind Android development, particularly focusing on creating user interfaces and the lifecycle of applications. The book is designed for those with some programming experience, aiming to equip readers with the necessary skills to build simple Android apps.

Uploaded by

koalgkhiun
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/ 83

Android Programming In Java Starting With An App

3rd Edition James download

https://ebookbell.com/product/android-programming-in-java-
starting-with-an-app-3rd-edition-james-23180262

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Bluetooth Low Energy In Android Java Your Guide To Programming The


Internet Of Things Tony Gaitatzis

https://ebookbell.com/product/bluetooth-low-energy-in-android-java-
your-guide-to-programming-the-internet-of-things-tony-
gaitatzis-55557680

Android Programming In Kotlin Starting With An App 1st Edition James

https://ebookbell.com/product/android-programming-in-kotlin-starting-
with-an-app-1st-edition-james-23180260

Android Programming For Beginners Build Indepth Fullfeatured Android 9


Pie Apps Starting From Zero Programming Experience 2nd Edition Horton

https://ebookbell.com/product/android-programming-for-beginners-build-
indepth-fullfeatured-android-9-pie-apps-starting-from-zero-
programming-experience-2nd-edition-horton-38076054

Reactive Programming In Kotlin Design And Build Nonblocking


Asynchronous Kotlin Applications With Rxkotlin Reactorkotlin Android
And Spring Rivu Chakraborty

https://ebookbell.com/product/reactive-programming-in-kotlin-design-
and-build-nonblocking-asynchronous-kotlin-applications-with-rxkotlin-
reactorkotlin-android-and-spring-rivu-chakraborty-6855722
Android Game Programming Extend Your Game Development Skills By
Harnessing The Power Of Android Sdk A Course In Three Modules Horton

https://ebookbell.com/product/android-game-programming-extend-your-
game-development-skills-by-harnessing-the-power-of-android-sdk-a-
course-in-three-modules-horton-11418766

Android Application Programming With Opencv 3 Build Android Apps To


Capture Manipulate And Track Objects In 2d And 3d Joseph Howse

https://ebookbell.com/product/android-application-programming-with-
opencv-3-build-android-apps-to-capture-manipulate-and-track-objects-
in-2d-and-3d-joseph-howse-5476342

Android Application Programming With Opencv 3 Build Android Apps To


Capture Manipulate And Track Objects In 2d And 3d 1st Edition Joseph
Howse

https://ebookbell.com/product/android-application-programming-with-
opencv-3-build-android-apps-to-capture-manipulate-and-track-objects-
in-2d-and-3d-1st-edition-joseph-howse-50195958

Kotlin And Android Learn To Architect And Develop Android Apps In The
Kotlin Programming Language Android Development With Kotlin Murdoch

https://ebookbell.com/product/kotlin-and-android-learn-to-architect-
and-develop-android-apps-in-the-kotlin-programming-language-android-
development-with-kotlin-murdoch-23720384

Kotlin And Android Learn To Architect And Develop Android Apps In The
Kotlin Programming Language Android Development With Kotlin Reuben
Murdoch

https://ebookbell.com/product/kotlin-and-android-learn-to-architect-
and-develop-android-apps-in-the-kotlin-programming-language-android-
development-with-kotlin-reuben-murdoch-27845784
Android Programming In Java:
Starting with an App

Using Android Studio 3

Third Edition

Mike James

I/O Press
I Programmer Library
Copyright © 2017 I/O Press
All rights reserved. This book or any portion thereof may not be reproduced
or used in any manner whatsoever without the express written permission of
the publisher except for the use of brief quotations in a book review.

Mike James Android Programming in Java: Starting with an App


3rd Edition
ISBN Paperback: 978-1871962550
First Printing, 2017
Revision 0

Published by I/O Press www.iopress.info


in association with I Programmer www.i-programmer.info

The publisher recognizes and respects all marks used by companies and
manufacturers as a means to distinguish their products. All brand names and
product names mentioned in this book are trade marks or service marks of
their respective companies and our omission of trade marks is not an attempt
to infringe on the property of others.
In particular we acknowledge that Android is a trademark of Google.

2
Preface

AndroidTM programming is an attractive proposition. There are more Android


users than any other smartphone or tablet and this makes it a potentially huge
market. Android devices are relatively cheap and this makes it suitable for
implementing smaller scale projects. Finally the tools that you need are free
to download and use and you don’t need anyone's permission to get started.
The only difficulty is that Android is a tough system to master. It is easy
enough to get started as Android Studio will build you a Hello World app in a
few minutes, but what you do next is more difficult. You can get a
surprisingly long way in Android programming by simply copying and
pasting code from other programs that roughly do what you want, but the
results are usually unreliable and disappointing. To create a good app there is
no substitute for understanding how the system works and appreciating its
strong points and its limitations.
This book aims not only to show you how common tasks are done in
Android, but to make sure that you understand why they are done in a
particular way. This means covering not just the “what” but also the “why”.
The good news is that this isn’t as difficult as you might expect because
Android does have repeating patterns and ways of doing things and once you
have seen something in action you find it generalizes to components you
haven’t encountered.
This isn’t a book full of complete examples and case studies. In fact the
examples are stripped down to their bare minimum to avoid having to present
lines of irrelevant and repetitious code and to let you see what is essential. It
also isn’t a complete treatment of everything Android. A single book that
covered every aspect of the Android system would be too large to pick up and
carry. Instead it tackles the things you need to know to write a simple app. It
focuses on creating the user interface (UI) because this is what you spend
most of your time working on even if the app in question is sophisticated. At
least 90% of the effort in creating any app goes into building and perfecting
the UI and this makes it the key place to start. In this book you will find out
how to build an app with a single Activity and a UI. If you master this level of
the art then you will find it much easier to push on into unknown territory. I
can’t promise to cover every aspect of the UI but I have tried to include
examples of all of the sorts of techniques you will encounter so that you are
familiar with the way things work in general.

3
This book is at an introductory level as far as Android development goes,
however it isn’t for the complete beginner. It is assumed that you can
program, but not necessarily in Java, which is arguably the most important of
all today’s programming languages and the original language of Android. Java
is a very standard object-oriented language and with the help of comments
that point out where it is significantly different you should find it easy to pick
up as you go along. Finally the development tool used is the latest version of
Android Studio because it doesn’t make sense not to use it or to use anything
else.
This edition has been updated to cover features introduced in Android
Studio 3. In particular, it includes the use of Java 8 and the lambda
expression which greatly simplifies event handling. As well as the latest
Android Studio it also covers ConstraintLaout 1.0.2 which includes Groups
and Barriers as well as a much improved editor.

Mike James
November 2017

This book is a revised and updated version of the series of Android


Adventures With Android Studio on the I Programmer website:
www.i-programmer.info.
There are additional articles on I Programmer that form the basis of the more
advanced books that are still in preparation. After updating and revision,
Android Adventures – Mastering Fragments will be published in print as
Android Programming: Mastering Fragments & Dialogs.
The first draft of Android Programming: Structuring a Complex App, which
goes further into threading, concurrency, life cycle and other topics crucial to
a real world app, is currently work in progress on the website.
To keep informed about forthcoming titles in the Android Programming
series visit the I/O Press website:
www.iopress.info
This is also where you will also find errata, update information to keep up
with changes in Android Studio and Android itself and, most importantly,
the code from the books. You can also provide feedback to help improve
future editions of Android Programming.

4
Table of Contents
Chapter 1
Getting Started With Android Studio 11
The Language Choice........................................................................12
What You Need to Know..................................................................12
Making a Start...................................................................................12
Your First Program............................................................................14
First Look...........................................................................................18
The IDE..............................................................................................19
Basic Project Structure......................................................................19
Anatomy of an Activity.....................................................................20
Hello Layout Designer.......................................................................21
Inspecting the XML...........................................................................26
The Java.............................................................................................26
Getting Started with the Emulator ...................................................28
Summary...........................................................................................31
Chapter 2
Activity and User Interface 33
The MainActivity..............................................................................34
Inside the Activity.............................................................................35
View and ViewGroup........................................................................36
Creating Our First UI.........................................................................37
Properties...........................................................................................41
Events................................................................................................42
Connecting the Activity to the UI.....................................................44
Finding View Objects........................................................................48
Summary ..........................................................................................50
Chapter 3
Building a Simple UI 53
What's in the Palette..........................................................................54
The Button an Example....................................................................56
Positioning – the ConstraintLayout..................................................56
Sizing.................................................................................................64
The Component Tree........................................................................66
A Simple Button Example – Baseline Alignment............................66
Orientation and Resolution..............................................................68
A First App – Simple Calculator.......................................................73
Summary...........................................................................................81

5
Chapter 4
Android Events 83
The Lambda Approach.....................................................................83
Lambda Types...................................................................................85
Using a Lambda to Create an Event handler....................................86
Closure...............................................................................................88
Event Handler Using A Class............................................................89
Using Breakpoints.............................................................................92
Alternative Ways to Handle an Event..............................................93
Implement the Interface in the Activity...........................................94
Anonymous Classes..........................................................................95
Code Folding.....................................................................................98
Which Approach Should You Use?..................................................99
Summary.........................................................................................100
Chapter 5
Basic Controls 101
Basic Input Controls........................................................................101
Button Styles and Properties..........................................................101
All Properties...................................................................................105
Text Fields.......................................................................................107
The onEditorAction Event..............................................................110
CheckBoxes.....................................................................................111
Switches and Toggle buttons..........................................................112
Radio Buttons .................................................................................113
Summary.........................................................................................115
Chapter 6
Working With Layouts 117
Understanding Layouts...................................................................117
Layout Properties............................................................................118
Width and Height............................................................................120
Units................................................................................................120
A Control is Just a Box....................................................................122
Gravity.............................................................................................123
The FrameLayout............................................................................124
LinearLayout....................................................................................126
RelativeLayout.................................................................................130
Summary.........................................................................................134

6
Chapter 7
The ConstraintLayout 135
Automatic Constraints....................................................................136
Manual Constraints.........................................................................140
Bias Constraints...............................................................................143
Chains..............................................................................................145
A Chained Keypad..........................................................................147
Guidelines........................................................................................150
Groups.............................................................................................151
Sizing...............................................................................................152
Barriers............................................................................................157
Constraint Properties......................................................................160
Troubleshooting..............................................................................160
Summary.........................................................................................162
Chapter 8
Programming The UI 163
A UI Library.....................................................................................163
The View.........................................................................................163
Using setContentView.....................................................................164
The ViewGroup...............................................................................166
Programming Layout Properties.....................................................167
The View Hierarchy........................................................................169
XML Layout.....................................................................................169
Inflation Theory..............................................................................170
Finding View objects.......................................................................171
How to Build a UI?..........................................................................172
Summary.........................................................................................173
Chapter 9
Menus – Toolbar 175
Creating a Menu Resource..............................................................175
The Menu Tree................................................................................176
Displaying a Menu..........................................................................178
Using the Toolbar............................................................................179
Creating the App Bar ......................................................................183
Where's My Toolbar?.......................................................................184
Responding to Menu Events...........................................................184
Changing Menus in Code................................................................187
Controlling the Toolbar...................................................................190
Summary.........................................................................................191

7
Chapter 10
Menus – Context & Popup 193
The Context Menu..........................................................................193
Contextual Action Bar.....................................................................196
The Popup Menu.............................................................................200
Summary.........................................................................................203
Chapter 11
Resources 205
Why Use Resources?.......................................................................205
What are Resources?.......................................................................207
Drawables........................................................................................208
Values..............................................................................................211
IDs....................................................................................................212
Accessing Resources in Code – The R Object................................213
Conditional Resources....................................................................214
A Simple Localization.....................................................................218
Android Studio Translation Tools.................................................219
Summary.........................................................................................221
Chapter 12
Bitmap Graphics 223
Android Graphics............................................................................223
The Bitmap......................................................................................223
The ImageView Control..................................................................224
Canvas..............................................................................................225
A First Graphic................................................................................226
Transformations..............................................................................229
A Logical Approach to Transforms................................................232
Setting Your Own Coordinates.......................................................233
Simple Animation...........................................................................234
Timer and Threads..........................................................................236
Listing..............................................................................................241
Summary.........................................................................................243

8
Chapter 13
Life Cycle Of An Activity
Lifetime and State...........................................................................245
The Life Cycle of an App................................................................246
The Simple Approach.....................................................................247
Lifecycle Explorer...........................................................................248
Trying It Out....................................................................................249
Retaining State – the Bundle..........................................................250
Saving Additional UI Data..............................................................252
Complex UI Elements.....................................................................253
Advanced State Management.........................................................254
Summary.........................................................................................255
Chapter 14
Spinners 257
The Spinner and the Designer........................................................257
Introducing the ArrayAdapter........................................................259
Handling the Selection...................................................................261
Creating an ArrayAdapter from a Resource...................................265
Changing The List...........................................................................265
Summary.........................................................................................267
Chapter 15
Pickers 269
Working with Pickers......................................................................269
TimePicker.......................................................................................270
TimePicker in Code.........................................................................271
Updating the Time..........................................................................272
DatePicker........................................................................................273
Number Picker.................................................................................277
Multi-Digit Input.............................................................................281
Summary.........................................................................................285
Chapter 16
ListView 287
Understanding the Adapter............................................................287
Extending the ListAdapter Class....................................................288
Using the ArrayAdapter..................................................................289
Working with the Data....................................................................291
A Custom Layout.............................................................................294
A Custom ArrayAdapter.................................................................297
Reuse, Caching and General Layouts.............................................301
Custom Adapter..............................................................................304
Summary.........................................................................................306

9
Chapter 1

Getting Started With Android Studio

Android represents a big potential market. It is also the most open of the "big"
phone and tablet platforms. You can write a program for an Android and let
your friends have a copy, keep it to yourself or put it on sale in an app store.
Android phones and tablets are comparatively cheap and this makes it easier
to get started. What is even better, all the tools you need to create an Android
app are free. You don't need to pay anything to create, or distribute, your
Android apps. If you want to sell them using a well known marketplace there
may something to pay – there is a one-time fee of $25 to register for Google
Play, but you don't have to use any particular distribution method.
All that stands between you and your Android app is your imagination and
programming ability. I can't do much to improve your imagination, but I can
help with the programming side of things. If you are new to Android
programming this is the place to start.
In this book I will show you the fundamentals of Android programming. Not
the tips and tricks, but how to think about what is going on. You'll be
introduced to the general principles that will make it possible for you to
master anything that you encounter that is new in the future. It isn’t possible
to cover all of Android in one book as the subject is very large. Instead we
focus on the basics of creating a User Interface (UI) as all apps have to have
some way of interacting with a user.
There are many ways to create an Android app but Google's Android Studio is
an easy to use Android IDE – Integrated Development Environment – and it is
now the recommended way of doing the job.
Before Android Studio you had to use the Eclipse IDE and set up the SDK and
other pieces of software needed. This wasn't difficult, but Android Studio
eliminates extra steps and it makes programming Android easy. Put simply, it
is the way of the future and so worth your investment in learning it.
With the release of Android Studio Google stopped work on the Eclipse
plugin and this means that Android Studio really is the only way to develop
apps from now on.
You can get started in a few minutes and by the end of this chapter, have your
first working Android application.

11
The Language Choice
With the release of Android Studio 3 you now have a choice of programming
in Java or Kotlin. The advantage of Java is that it is a well known and well
supported language. In Android Studio 3 you can also program using features
from Java 8 including lambda functions. This greatly simplifies tasks such as
event handling and, while we will examine how to do event handling in Java
without lambda functions, using them is going to be the norm.
As the entire Android library is written in Java you really can’t avoid it. The
alternative language Kotlin is very easy to use and backwards compatible
with Java. There is very little risk in using it, but it is also helpful to know
enough Java to work with existing code.
The bottom line is that while Kotlin is an easier language to use, there are
advantages in knowing and using Java.

What You Need to Know


To get the most out of this book you need to be able to program in a modern
object-oriented language. You’ll have a head start if you already know some
Java, but C++, C#, Visual Basic or anything similar are close enough in spirit
to Java for you to be able to cope. You might well need to look things up
about the specifics of particular features of Java, but most of the time it
should be obvious, or obvious with the help of a few comments.
It isn't necessary to be an expert programmer because for a lot of Android
programming you are simply using the features and facilities provided. That
is, a lot of Android programming is just a matter of following the rules.
However, if you hope to produce something unique and useful you will at
some point have to add something of your own – and here creativity and skill
are required. So you might not need to be an expert programmer to get
started, but you need to become one by the time you create your amazing app.
Fortunately practice is a good teacher and so learning to make the most of
Android Studio will actually help you learn to code.

Making a Start
I'm not going to spend a lot of time explaining how to install Android Studio
in a step-by-step way as the Android website does a good job and it is more
likely to be up-to-date. It is worth, however, going over the basic principles.
Download the Android Studio package from Android Studio Home page:
https://developer.android.com/studio/
Install Android Studio which also installs all of the Android SDK and tools
you will need.

12
Windows:
1. Launch the downloaded EXE file,
android-studio-bundle-<version>.exe.
2. Follow the setup wizard to install Android Studio.
Mac OS X:
1. Open the downloaded DMG file,
android-studio-bundle-<version>.dmg
2. Drag and drop Android Studio into the Applications folder.
Linux:
1. Unpack the downloaded ZIP file,
android-studio-bundle-<version>.tgz,
into an appropriate location for your applications.
2. To launch Android Studio, navigate to the
android-studio/bin/
directory in a terminal and execute studio.sh. You may want to add
android-studio/bin/
to your PATH environmental variable so that you can start Android
Studio from any directory.
Accept any defaults that the setup program offers you – unless you have a
good reason not to. It installs not only Android Studio, but the SDK and the

13
virtual device system that lets you test your application. In most cases
Android Studio just installs with no problem.
Now you should be able to run Android Studio. If not the most likely cause of
the problem is the JDK and so re-installation is a best first option.

Your First Program


You can opt to start Android Studio after the installation. You will probably
not get straight to Android Studio the first time it starts as it downloads
updates to itself and to the Android SDK. You just have to be patient.
When it finally gets going you will see the Android Studio welcome screen:

If you have already created some programs you might well see them listed in
Recent projects.

14
Assuming this is your first project select the option:
Start a new Android Studio project

You can ignore the details of the new project for the moment. All you have to
do is supply a name for your application - HelloWorld in this case. Make sure
you uncheck the Include Kotlin support option as you want to make use of
Java. Accept the other defaults that Android Studio has filled in for you.
When you click Next you are given the chance to pick what devices you are
targeting. Again simply accept the defaults:

15
Most of the time you will want to create apps that run on a version of Android
that captures the biggest market, but if this isn't a concern then it can be
better to select a more recent Android version.
The next page lets you select a template for your project. In this case change
the selection to Basic Activity. This gives you some additional generated code
which makes it easier to create an app that looks right. Every Android
application consists of at least one Activity and this template generates a
project with a single Activity ready for you to customize:

On the next page you can assign custom names for the various components of
your project that the template generates. For a real project you would assign
names that were meaningful, but in this case you can accept the defaults:

16
Finally you can click the Finish button and wait as Android Studio creates all
the files you need. Even a simple Android project has lots of files so again it
all takes time.

17
First Look
When everything is ready you will see Android Studio for the first time.
As long as everything has worked you should eventually, it takes about three
minutes or more, be presented with a view of your new project starting off in
the Designer. Click the Design tab to see the initial user interface:

Problems?
If you get any error messages then the chances are that your project hasn't
finished being processed. Wait a little while longer for the activity to stop. If
you look at the status line at the bottom of the window you will see a message
saying “Gradle Build Finished” when Android Studio has finished with your
new project.
If you still have problems it is worth trying the File,Invalidate Caches/Restart
command. This usually works for "Missing styles" and similar errors.

18
The IDE
Although there looks like a lot to master in the Android Studio user interface,
most of it you will only visit occasionally. The key things to notice are that
moving from left to right you have:
● The Project window
● The tool Palette and the Component Tree window
● The Designer or Layout Editor
● The Attributes window
Most of the time you will be using the Project window and the Attributes
window. You will also see different editors depending on what sort of file
you have selected. In this case you have by default a layout file,
content_main.xml, selected and hence you have a layout editor in the middle
of the screen.
Before we go into layout, which is one of the main topics of this book, it is
important that you know a little about the file structure of a project so that
you can navigate to its different parts.

Basic Project Structure


When the project has finished building all of the files created can be viewed
by opening the Projects tab. The main thing to notice is that there are a great
many folders and files:

It seems almost unbelievable that the simplest Android app you can create
involves so many files.

19
Don't panic. Most of the files that have been created are auto-generated and
most of the time you don't need to know anything about them, let alone open
or edit them. In fact, opening and editing auto-generated files really isn't a
good idea.
So let's focus on the files that matter to us.
For our simple program there are only two important files. One of them
determines the behavior of the Activity:
MainActivity.java
The other determines the visual appearance, or View, of the app:
content_main.xml
You can set which Activity is the one that the system starts, but by default it
is the single activity that you created and named when you set up the project.
You can change the default names but for the moment leave them as they are.
The java directory is, from your point of view, where most of the construction
of your app occurs so make sure you know where it is. The res directory is
where you store all of the resources, layouts, bitmaps, etc, that your app
needs.
So while things look complicated at the moment the only two project files
that matter to you, and your project, are MainActivity.java in the java folder
and content_main.xml in the res folder.
The two other folders in the java folder are concerned with creating tests for
your program. This is not something that we need to worry about when first
starting to write Android apps.

Anatomy of an Activity
An Android app is made up of one or more Activity classes.
You can think of an Activity as being something like a web page complete
with HTML to determine what displays and JavaScript to determine what it
does.
In the case of an Activity the layout is determined by the XML file in resource
(res) folder, this is often called the View, and the behavior is determined by
the code in the java folder.
The XML can be thought of as a markup language much like HTML or XAML.
It defines an initial layout for the screen when the app first runs. It is possible
to generate new layout components at runtime from the Java file. In fact, if
you really want to, you can dispense with the XML file and generate
everything from code, but as you will discover the XML markup approach is
much the best way to do the job because of the availability of the Designer.

20
So to be 100% clear in a Java project:
● The java file contains the code that makes your app behave in
particular ways.
● The .xml layout file contains a definition of the initial UI, the View, of
your app.

Hello Layout Designer


Let's take a look at the two files that have been generated for our initial Hello
World application, beginning with the XML layout. Double click on the
content_main.xml file in the Project tab and the file will open (if it isn't
already open). If it is already open you can also select its tab displayed just
above the editor area. You can select any file that is open for editing by
selecting its tab.
You can work with the XML directly to define where all the buttons and text
go, and later you will learn how to edit it when things go wrong or to fine
tune it. However, Android Studio provides you with a very nice interactive
Layout Editor, which throughout this book is referred to as the Designer and
this is worth using.
As you become more experienced the idea of switching between a design
view and an XML view will become second nature. Think of the interactive
editor as a very easy way of generating the XML that otherwise would take
you ages to get right. If you look at the bottom left you will see two tabs –
Design and Text:

You can switch between editing the XML as text, and editing it in the drag-
and-drop designer simply by clicking on the tab. If you now click on the tab
the window will display the Designer, but be patient the first time you do this
it might take a few moments.

21
The Designer looks a little too much to take in when you first see it but you
will quickly get used to it. On the left is a Palette of all of the components or
controls - buttons, text, checkboxes and so on - that you can place on the
design surface:

In the middle is the design surface and this defaults to the screen size and
appearance of the Nexus 5. You can select other devices to work with.

22
There are, in fact, two views of the layout that you can use, the design and the
blueprint. By default you are shown the design view but you can display
either view using the menu at the top left of the design area.

You can display both views together, but in most cases available screen area
is the main issue and showing just one is the best option. The design view
shows you the layout as a close approximation to how it will appear on a real
device. The blueprint view doesn’t try to render the UI realistically but it does
provide you will more layout information to help you position and size
elements. Use whichever you are most happy with.

23
On the left, below the Palette, you have the Component Tree which shows
you the structure of your layout, that is how different UI components are
contained inside others. It shows you the structure of the XML file in an
easier to use form. You can use the Component Tree as an easy way of to
select individual UI components by clicking on their names. You can also
drag-and-drop UI components onto the Component Tree to position them
accurately within the hierarchy.
On the right you have the Attributes window that can be used to set the
properties, such as width, height, color and so on of any component in the
layout. If you have used any drag-and-drop designer then this will seem
familiar and if you have struggled with detailed layout using a markup
language, be it HTML, XAML or XML, you will appreciate how easy the
Designer makes building and testing a UI.
In the case of our sample program the only component is a single TextView
already containing the text "Hello World". A TextView is the standard
component to use when all we want to do is to display some static text.

24
You can modify the greeting text if you want to. Select the TextView
component either on the Nexus image or in the Component Tree and use the
Attributes window to find its Text property. Change this to read "Hello
Android World!":

Use the text field without the spanner icon. The properties with the spanner
icon next to them are used to set values that only show in the Designer. In
this case the text field without the spanner icon is the one that controls what
appears in your app at runtime.
You can use the Designer to create any UI you care to and you really don't
have to get involved in the XML that corresponds to the layout – unless things
go wrong or you need to do something so sophisticated that the Designer
doesn't support it.

25
Inspecting the XML
The Designer will automatically generate the XML needed to create the layout
for you and modify it as you change the layout. If you really want to see the
XML then all you have to do is select the Text tab at the bottom of the
Designer window:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.mikejames.helloworld1.MainActivity"
tools:showIn="@layout/activity_main">

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

</android.support.constraint.ConstraintLayout>
You should find it fairly easy to understand – read the <TextView> tag for
example – but leave it to the Designer to create and modify it. The quantities
starting with @ are all references to things defined elsewhere in resource
files, more of this in chapter 11.
We will return to the Designer and the XML it generates later.

The Java
If you double click on the MainActivity.java file, or just select the
MainActivity.java tab, you will see the code it contains. Some of the code
might be hidden, but you can inspect it if you want to by clicking the +
button to expand it.
The important part of the code is:
public class MainActivity extends AppCompatActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

26
You can ignore the instructions that follow the setContentView function
because these set up the standard "extras" that every Android application now
supports – a floating ActionBar.
There are two other functions below the onCreate function, but ignore these
for the moment. They implement features you didn't really ask for which can
be useful, but not when you are just getting started.
The onCreate function is the only thing that matters at the moment. This
function is called when your app is run and it is expected to create the view
and do the actions the Activity is concerned with.
As our Activity doesn't really do anything much the only thing onCreate has
to do is first call the inherited OnCreate method, super.onCreate, to do all the
standard things and then use the setContentView function to select the XML
file that determines the layout of the Activity’s screen.
The line:
setContentView(R.layout.activity_main);
is the most important of all and really the only one that actually does
anything. It gets the resource object R that represents the layout as defined by
the XML file created by the Designer and makes it the current ContentView,
i.e. what is displayed on the screen. In other words, it makes the connection
between the layout you have defined using the Designer and stored in the
XML file, and the user interface that appears on the device’s screen.
You may be puzzled as to why you edited a resource file called
content_main.xml and yet the Java is loading a resource file called
activity_main.xml.
The answer is that, to make extending your app easier, Android Studio
creates two layout files, activity_main.xml that creates the "standard" controls
that are displayed and content_main.xml that you use to design your custom
UI. Of course, activity_main.xml contains a reference to content_main.xml.
This makes things more complicated for the beginner, but is a simplification
later on.
We have more to learn about the resource object R, but you can see that its
main role is to form a link between your Java code and the resources that
have been created as XML files by the Designer.
As this is all our Activity does, this is all the code we need. While I agree it is
hardly an "activity", it is enough to see the basic outline of an Android app
and to see how to get it running – which is our next job.

27
Getting Started with the Emulator
There are two distinct ways of running an Android app using Android Studio.
You can use the emulator or a real Android device. Eventually you will have
to discover how to run an app on a real connected Android device because
the emulator only allows you to test a subset of things and it is slow.
However, for the moment running your first app on an emulator is quite
enough to get started.
All you have to do is click the green run icon in the top toolbar – or use the
Run,Run "app" menu item. When you do this for the first time it will take a
while for the app to be compiled. Subsequent runs are much faster due to
optimizations introduced in Android Studio 2.
When your app is ready to be compiled you will see a dialog box appear
which allows you to either select a running emulator or start one going:

If no emulators are listed then you will have to create one. Select the Create
New Emulator button. This will present a dialog box where you can select the
device you want to test on.
The default is the Nexus 5 running API 25, Nougat, and for a first test you
might as well use this. If you need other devices you can use the AVD
(Android Virtual Device) Manager to define them.
If you see a message on the right of the screen “HAXM is not installed” then it
is a good idea to click the Install Haxm link just below. HAXM is an
accelerator that is used on Intel machines to make the Android Emulator run
faster. You don’t need it, but it does speed things up:

28
You can accept all of the defaults in this first run. You can monitor the
loading of the emulation in the Run window which appears automatically at
the bottom of Android Studio. You may see some warnings appear – these can
mostly be ignored.
The whole process takes some time the first time you do it. After the first time
the emulator is already running and the instant run feature tries to re-run
your app with the minimum changes:

29
Remember to wait until the Android operating system is loaded and you see
the familiar home screen before you start to wonder where your app is. Even
when it is loaded it is a good idea to give it a few seconds for Android Studio
to notice it and to upload your app:

In our case this isn't particularly impressive – just the words “Hello Android
World!” - but when you think of the journey traveled it really should
impress.
From this point on you can modify the code or the layout and run the app
again to see the effects of the changes. If anything goes wrong and you get in a
mess then simply delete the project and create it again from scratch.
You still have a lot to discover about how to extend the app and make it
useful, but the adventure has begun.

30
Summary
● Android Studio makes creating Android apps a lot easier than other
approaches and it is currently the only official way to do the job.
● An app has at least one Activity and this defines a screen layout, the
View, and a behavior. An Activity doesn't have to have a UI, but in
most cases it does have one.
● To create a simple application use the Basic Activity template with no
extras selected.
● The screen layout is controlled by an XML markup file,
Main_Activity.xml, stored in the res directory. There is also
content_main.xml, which is where we place our custom UI controls.
● Android Studio provides a drag-and-drop designer that allows you to
create a UI without having to work directly with the XML.
● The behavior of the app is controlled by a Java file, MainActivity.java
in our case, stored in the java folder. You can edit the code in the Java
file directly in Android Studio. The Java code has to load and display
the layout defined in the XML file.
● To run an app you need either an emulator based AVD or a real
Android device connected to the machine.
● When you run the app you can select which AVD or which hardware
device is used to test it. When you first start simply use the default
AVD, a Nexus 5.
● You can modify and re-run your app without having to restart the
AVD or any real hardware connected to the machine.

31
Chapter 2

Activity and User Interface

So you know how to create an Android app, but do you really know how it
works? In this chapter we look at how to create a user interface (UI) and how
to hook it up to the code in the Activity.
We discovered in Chapter 1 how to use Android Studio to build the simplest
possible app. On the way we discovered that an Android app consists of two
parts – an Activity and a View. The Activity is the code that does something
and the View provides the user interface (UI). You can think of this duality as
being similar to the HTML page and the JavaScript that runs to make it do
something, or as a XAML form and the code behind.
The key idea is that an Activity is the code that works with a UI screen
defined by the View. This isn't quite accurate in that an Activity can change
its view so that one chunk of code can support a number of different views.
However, there are advantages to using one Activity per view because, for
example, this how the Android back button navigates your app – from
Activity to Activity.
A complex app nearly always consists of multiple Activities that the user can
move between like web pages but a simple app can manage quite well with
just one Activity. There is no hard and fast rule as to how many Activities
your app has to have, but it has to have least one.
If you are wondering if an Activity can exist without a View, the answer is
that it can, but it doesn't make much sense as this would leave the user with
no way to interact with your app. An Activity is active when its View is
presented to the user.
It really is a great simplification to think in terms of an Activity as a single
screen with a user interface.
If you want something to run without a UI then what you want is a service or
a content provider, which is beyond the scope of this book.
It is also worth making clear at this early stage that an Activity has only one
thread of execution – the UI thread – and you need to be careful not to
perform any long running task because this would block the UI and make
your app seem to freeze. That is, an Activity can only do one thing at a time
and this includes interacting with the user. If you write a program using a
single activity and it does a complicated calculation when the user clicks a

33
button then the activity will not be able to respond to any additional clicks or
anything that happens in the UI until it finishes the calculation.
In most cases the whole purpose of the Activity that is associated with the UI
is to look after the UI and this is what this book is mostly about.
Also notice that creating additional Activities doesn't create new threads.
Only one Activity is active at any given time, more of this later when we
consider the Activity life cycle in detail.
In this book we are going to concentrate on the single screen UI Activity
because it is the most common app building block you will encounter, and it
is even where most complex apps start from.

The MainActivity
There is one activity in every project that is nominated as the one to be
launched when your app starts. If you use Android Studio to create a new
Basic Activity app called SimpleButton and accept all the defaults, the
startup Activity is called MainActivity by default. You can change which
Activity starts the app by changing a line in the app's manifest.
The Manifest is a project file we haven't discussed before because if you are
using Android Studio you can mostly ignore it and allow Android Studio to
construct and maintain it for you, but it is better if you know it exists and
what it does.
The Manifest is stored in the app/manifests directory and is called
AndroidManifest.xml.
It is an XML file that tells the Android system everything it needs to know
about your app, including what permission it requires to run on a device.
In particular it lists all of the activities and which one is the one to use to start
the app.
If you open the generated Manifest, by double-clicking on it, you will see a
little way down the file:
<activity
android:name=".MainActivity"
android:label="SimpleButton" >

This defines the Activity the system has created for you and the lines just
below this define it as the startup Activity:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

34
Notice that the choice of which Activity starts the app has nothing to do with
what you call it, i.e. calling it MainActivity isn't enough.
For the moment you can rely on Android Studio to look after the Manifest for
you. In most cases you will only need to edit it directly when you need to
correct an error or add something advanced.

Inside the Activity


The generated Activity has one class, MainActivity, which holds all of the
methods and properties of your activity.
It also has three generated methods:
● onCreate
● onCreateOptionsMenu
● onOptionsItemSelected
The last two are obviously connected to the working of the OptionsMenu,
which is an important topic but one that can be ignored for the moment. Not
all Activities need to have an OptionsMenu and you could even delete these
methods if you don't want to support an options menu.
All three of these methods are event handlers. That is they are called when
the event that they are named after occurs. The whole of an Android app is a
collection of nothing but event handlers and their helper functions.
The most important method generated by Android Studio is onCreate. This is
an event handler and it is called when your app is created and is where we do
all the initialization and setting up for the entire app. It is also generally the
place we show the app's main UI screen.
Let's take another look at the first two lines of generated code for onCreate,
which are the most important:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
The onCreate event handler is passed a Bundle object called
savedInstanceState. This is intended to preserve state information between
invocations of your app and we will see how this is used later. In this case no
data has been saved and so savedInstanceState is null – but you still have to
pass it on to the inherited onCreate method. You will learn a lot more about
Bundle in Chapter 13.
The final instruction calls setContentView, which is a method that has a
number of different overloaded forms. In this case we pass an integer that
indicates which XML file describes the layout to be used for the view. The
setContentView method uses this to create all of the components of your UI
as defined in the XML file. That is, this is the connection between the layout

35
you created using the Designer and the layout that appears on the device's
screen.
It is worth looking a little closer at the way that the layout file is specified
because this is a general way that Android lets you access resources. There is
a whole chapter about resources later but it is still worth an introduction
now.
The R object is constructed by the system to allow you to access the resources
you have placed in the resource directories. For example, in onCreate the use
of R.layout.activity_main returns an integer value, its id, that allows the
setContentView method to find the activity_main XML layout file. In general
all resources are found via the R object, think of it as an index of resources.

View and ViewGroup


So far so good, but it is important to realize that what happens next it that the
XML file is rendered as a set of View objects. That is, Java objects that are all
sub-classes of the View object. The entire UI and graphics system is
implemented as a hierarchy of components derived from the View class. If
you have used almost any GUI framework, AWT, Swing, XAML, etc, this idea
will not be new to you. For example, a button is a class derived from View
and to create a button all you have to do is create an instance of the Button
class. You can of course create as many buttons as you like simply by creating
more instances.
This leaves open the question of where the button appears in the layout?
The answer to this is that there are ViewGroup objects which act as
containers for other View objects. You can set the position of the child View
objects or just allow them to be controlled by various layout rules, more of
which later. You can opt to create the entire UI in code by creating and
working with instances of View objects and this is something demonstrated in
Chapter 7.
So to be 100% clear all of the UI objects are defined in code and every UI
object, such as a button, has a Java class with a similar name that lets you
create the UI in code. In fact this is the only way to create the UI, but there
are other ways of specifying it. Instead of writing code to create the UI you
can specify what you want in an XML file and then use supplied code to
display it. This is what setContentView does – it reads the XML file you
specify and creates Java objects that implement the UI.
This means you could create the UI by manually writing an XML file
that defines view objects and how they nest one within another and rely on
the system to create the view object hierarchy for you. Although this is
possible, it is much easier to use the Designer to create the XML file and then
allow the system to create the objects for you from the generated XML file.

36
That is, you can drag-and-drop a button onto the Designer and it will
automatically generate the XML needed to create it and specify where it is
and all of the other details you set.
That is, at the surface level there are three ways to create the UI:
1. You can write Java code to generate the necessary Java objects.
2. You can write XML tags and use the system to convert the XML to the
same Java objects.
3. You can use the Designer to interactively create the UI and generate
the XML file which is then converted into the Java objects
needed. You can think of this as:
drag-and-drop layout -> XML -> Java View objects
Being able to work with the UI in an interactive editor is one of the great
advantages of using Android Studio and, even if you know how to edit the
XML layout file directly, it isn't a feature you should ignore. It is nearly
always a good idea to use the layout editor as the first step and apply any
tweaks, if necessary, to the XML file later.

Creating Our First UI


To see how all of this fits together let’s add a button and a textView object.
You probably already know that a button is for pressing and you can guess
that a textView is used to show the user some text.
First remove the Hello World text that is generated automatically when you
create a new blank Activity. Load the content_main.xml file by opening it
from the project view.

37
The content_main.xml is where you create all of your UI. There is another
layout file, but as explained in Chapter 1 this simply provides the standard
elements in a UI like the AppBar. Notice that because of this you can see UI
components in the Designer that you cannot edit - they belong to the other
layout file.
To remove "Hello World" all you have to do is select it and press the delete
key:
Notice that there is an undo command, Ctrl-Z, if you delete something by
mistake.
Next select the button in the Widgets section of the Palette by clicking on it
and drag it to the design surface:

38
If you now place the cursor over the design area you will discover that as you
move it various alignments are indicated by lines:

To position the button simply click and a full button, complete with the
default caption Button, will appear.
However, simply dropping the button on the design surface isn't quite
enough. If you just do this the button will be positioned but without any
positioning constraints. If you try running the program you will find that the
button sometimes vanishes on the emulator or real device. The reason is that
with no constraints to its positioning applied it rises to the top of the screen
and is hidden behind other controls.
This behavior is characteristic of the ConstraintLayout, more of which later.
For the moment we just need to apply some constraints to the button.
The simplest solution is to click on the Infer constraints icon and let Android
Studio work out how to position the button:

When you click this button constraints are added according to where the
Button is positioned. At the moment exactly what constraints you end up
applying matters less than the simple fact that there are some.

39
In the screen dump below the button is constrained to be a fixed distance
from the top and right-hand side. Notice that you can position the button and
then click the Infer constraints button to set the constraints needed to keep
the button in its location:

Now you have a button on the UI ready to go, let's add a TextView Widget in
exactly the same way – click on its icon in the Palette, position in the
Designer and click to set the position. Notice that Android Studio provides
positioning information to help you align components of the UI. Again you
need to click the Infer constraints icon to position the TextView. The simplest
thing to do is position the TextView where you want it and then click the
Infer constraints icon to set the constraints needed for that position:

40
Notice that Android Studio provides positioning information to help you
align components of the UI. The simplest approach to creating a layout is to
place the components where you want them and then click the Infer
constraints icon to apply constraints to fix their position. In practice these
constraints may not be exactly what you need but it gives you a starting point.
That's about it and in fact creating a complete complex UI is just more of the
same, just a matter of picking components from the Palette and positioning
them on the design surface.
If you now run the program, by clicking the green Run icon (refer back to
Chapter 1 if you don't know how to do this) you will see your new UI:

Of course it doesn't do anything, even if you can click the button. The button
does click, but there is no code connected to the button click event to say
what should happen, something we will deal with very soon.

Properties
Our next task is to change the caption on the button. Recall that objects have
properties and methods. Things like caption text, background color and so on
for UI widgets are represented as properties. You can change properties in
code, or at design time you can use the Attributes window on the right-hand
side of the screen.

41
If you select the button and examine the Attributes window on the right you
will find the button's text property. This currently contains the value
"Button". If you change this to "Click Me!" and re-run the app you will see that
the Button's caption has changed:

You can set the initial properties of any of the widgets that you have placed in
the UI. There are a great many properties and we need to spend some time
looking at some of them. However, for the moment the important thing is that
you see how easy it is to change a property using the Attributes window.
As you might guess, the property that you changed results in a change in the
XML file defining the layout. Recall that the general principle is that the
Designer creates the XML file that you could have created by hand without
any help from the Designer. In this sense, the Designer doesn't add anything
to the process, other than being much easier.

Events
Now we want to do something when the button is clicked. Android supports
a complete event-driven UI. So what we need to do next is define a method,
or function, that is called when the button is clicked.
If you are familiar with other languages you might find the Java way of
working with events strange and convoluted. It is, and we will have to come
back to discover the full story of how events are implemented later. The good
news is that Java events are much simpler in Java 8 and now Android Studio
supports this. While you do need to know the original ways of creating event

42
handlers it is always much easier to use Java 8 and its lambda functions in
particular. How to create event handlers is discussed in detail in Chapter 4.
There are a number of different ways to specify an event handler, but the
simplest is to use the Designer to generate the XML needed for the system to
hookup the event handler to the event. This is not an approach that you can
use all of the time. It only works for the click event, but it gets you started.
If you have used something like Visual Studio, it is also worth pointing out
that Android Studio doesn't automatically create event handlers for you. In
the case of Android Studio you have to create a function and then assign it as
the onClick handler. The reason for this apparently unhelpful approach is
that Java events are much more involved than .NET or JavaScript events.
Using the Designer approach, method click event handlers are simply public
methods of the current Activity with the signature:
void method( View v)
Just in case you have missed or forgotten what a function's signature is:
A function’s signature is the number and types of the parameters it accepts.
Functions with the same name but different signatures are considered to be
different functions. In this case the function takes a single parameter, which is
a View, and returns void, i.e. nothing.
You can call the method anything you like, but in most cases it helps to
specify exactly what the event it handles is. In this case we want to handle
the button's onClick event – which occurs when the user clicks on the button
with a mouse or more likely taps on the button using a touch sensitive
device.
Load the MainActivity.java file into the code editor and add the following
method:
public void buttonOnClick(View v) {
// do something when the button is clicked
}
This needs to be added directly following the onCreate method, or anywhere
that makes it a method of the MainActivity class.

43
With all this code out of the way, now switch back to the Designer, select the
button, find the onClick property in the Attributes window to enter or select
buttonOnClick:

Sometime the IDE is slow to notice that there is a suitable method and you
have to type the method’s name in. Notice that you don't type in parameters,
just the name of the method.
That's all there is to it. You define your event handler with the correct
signature and return type and set the appropriate onClick property in the
Attributes window.
When it comes to other types of event you have to do the job in code – the
XML/Designer method only works for onClick.

Connecting the Activity to the UI


Now we have an event handler hooked up to the button click event we
usually want to do something that affects the UI as a result.
Let's suppose that when the button is clicked we want to change the text
displayed in the TextView widget to "I’ve Been Clicked!".
We can do this by changing the TextView widget's text property to the new
text. The only problem is how do we find the TextView widget in code?
This is a fairly standard problem when you use a markup language to define a
UI. The markup language defines widgets, or other UI objects, and the code
has to have a way of making the connection to those UI objects. For example,
in JavaScript you make use of the getElementById method to retrieve a DOM
object corresponding to a particular HTML element.
In Android we do something similar.
First make sure you follow the idea that all of the XML generated by the
Designer gets converted into a set of Java objects, one for each component or
View placed on the design surface. These objects have the same range of
properties as you saw in the Attributes window and have methods to get
other things done. All you need to do is find a way to reference one of them.

44
In the case of the View object that caused the event this is very easy as it is
passed to the event handler as the only argument of the call. So if the event
handler is:
public void buttonOnClick(View v) {
and the event handler is only hooked up to the button, then you can be 100%
sure that v is the button object when the event occurs. If you want to change
the button's caption you could just use its setText method to change its
value.
Note: if you aren't used to Java then it is worth pointing out that generally all
Java frameworks follow the rule that if an object has a property called
myProperty, visible as such in the Attributes window, then in code you set it
using setMyProperty and retrieve it using getMyProperty.
So, in principle, all you have to write is:
v.setText("I've Been Clicked!");
However, this doesn't work because v is declared to be a general View object
which doesn't have a setText method – not all View objects have text to set.
To call the Button's setText method we have to cast v to its correct type,
namely a Button.
Note: Casting is where you tell the system the type of the object you are working
with. If classB is a subclass of classA then you can treat a classB object as a
classA - after all it has all of the methods and properties that classA does by
inheritance. However, if you want to make use of a property or method that
only classB has then you need to cast the reference to the classB object to make
its type clear.
For example, assuming classB inherits from classA:
classA myObject = new classB();
creates an instance of classB but myObject is declared to be of type classA. This
is fine but you can only access the methods and properties of the classA object.
However, if you try:
myObject.classBMethod();
then it will fail if classBMethod only exists in classB. To use the classB method
you have to cast myObject to its real type:
(classB) myObject
You can store a reference to the cast in a new variable:
classB myClassBObject = (classB) myObject;
and then call the method:
myClassBObject.classBMethod();
or you can just do the cast on the fly at the cost of an extra pair of parentheses:
((classB) myObject).classBMethod();

45
If you simply change the code to cast the v object to a Button object, i.e.
(Button) v, you will discover that Android Studio flags an error by showing
Button in red. If you hover over the red symbol you will see the exact error
message:

This is because you have used a class without importing it. You may see other
classes, View, for example highlighted in red as which classes are imported
by default depends on the exact project template you are using.
Any class that you use has to be listed at the top of the program in an import
statement. Whenever you see a "Cannot resolve symbol" error message the
most likely cause is that you haven't imported the class.
This can be a tedious business but Android Studio has some help for you. If
you click on the error symbol you will see a blue hint message:

If you look at the hint message it suggests pressing Alt+Enter which is always
good advice because it produces a list of possible fixes for the problem:

You can implement the fix simply by selecting it from the list.
In this case you have to add the class definition to the start of the program.
import android.widget.Button;
You can do this manually, i.e. you can type it in, or just select the first option.
The import is added and in a moment the red errors disappear.

46
If you hover over the corrected Button class name you will also see a light
bulb:

Android Studio offers you hints on improving your code even when there are
no errors – look out for the light bulbs. If you click on this one it will offer to
split the declaration and the assignment as being better style. Android Studio
is full of hints and offers to make your code better at every turn – you don't
have to accept them.
For the moment let's stick with the single line:
Button button=(Button) v;
Now we have the button object we can call its setText method:
button.setText("I've Been Clicked!");
The complete event handler is:
public void buttonOnClick(View v) {
Button button=(Button) v;
button.setText("I've Been Clicked!");
}
Now if you run the program you will see the button's caption change when
you click the button.
This is a common pattern in making your UI work – event handlers change
the properties of View objects to modify the UI. Notice that this approach
only works if you know the type of the object that caused the event and called
the event handler. If your event handler is only connected to a single
component then you do know the type of the object that caused the event. If
it isn't, or if you want to modify the properties of a View object that isn't the
subject of the event, then you have to find it. This is exactly what we are
going to do next.

47
Finding View Objects
Now suppose we want to do something to one of the other components in the
View. In this case we have to find the object that represents the component
without the help of the event handler's argument. For example how do we
find the TextView that we placed below the button?
In the event handler the Button is the object that caused the event to happen
so it is already found, but how do you find another component in the layout?
This is a very standard pattern in working with View objects from the
Activity. First you make use of the R object to find the component's id. In this
case the TextView has been given the id textView by default so we can use:
R.id.textView:
and this returns a unique integer that identifies the component.
Next we use the Activity’s
findViewById(int)
method which takes the integer id and returns the Java object corresponding
to id.
Of course this is returned as a View object because findViewById doesn't
know the type of the object it returns any more accurately. So we have to cast
to make use of the TextView object.
Putting all this together gives:
TextView myTextView=(TextView) findViewById(R.id.textView);
Once again Android Studio will complain about TextView and if you press
Alt+Enter it will add the class import to the start of the program for you:
import android.widget.TextView;
Now that you have the TextView object you can use the setText method to
change what it displays:
myTextView.setText("You Clicked My Button!");
The complete event handler is:
public void buttonOnClick(View v) {
Button button=(Button) v;
button.setText("I've Been Clicked!");
TextView myTextView=(TextView)findViewById(R.id.textView);
myTextView.setText("You Clicked My Button!");
}

48
If you now run the program you will see that you are informed twice of the
fact that this very important button has been clicked:

You may think that this is all very small stuff and nothing like a real app, but
this is how building a UI works in Android.
You now know how to design a single screen app using the widgets available
in the Designer’s Toolbox and how to hook them up to handle their click
events, find the Java object that represents them and how to call methods that
modify them.
Apart from the fine detail of how each of the widgets works – radio buttons,
checkboxes and so on – you now have the general outline of how to build a
single screen app.

49
Summary

● An Activity is the unit of the Android app and it roughly corresponds


to one screenful of user interface plus the code to make it work.
● In most cases you will create an Activity for each UI screen you want
to present to your user.
● Only one Activity from your app is running at any given time.
● An Activity is single-threaded and runs on the UI thread.
● You can set which Activity starts the app in the Manifest. Android
Studio sets this to MainActivity by default.
● The Activity has events corresponding to different stages in its life
cycle. The onCreate event is called when the app first starts and this
is where you perform all initialization.
● You can also restore the app’s state from previous runs at this point.
● The Activity then loads a View or ViewGroup object to create its user
interface.
● You can create View/ViewGroup objects in three possible ways: in
code, using XML or using the Designer to generate the XML.
● The Designer is far the easiest way to create a UI.
● By opening the XML file you can use the Designer to place widgets
corresponding to View objects on the design surface.
● You can use the Attributes window to set the properties of each
widget.
● The XML file that the Designer creates is used by the Activity to set its
UI by creating Java objects that correspond to each of the View objects
placed using the Designer.
● When you reference a class that isn't defined in the file, i.e. most of
them, then you need to add an import statement to the start of the
code.
● If you use Alt+Enter when the cursor is positioned within any word
that is displayed in red then Android Studio will help you fix the
problem.

50
Exploring the Variety of Random
Documents with Different Content
Conditions precedent to Proof.
Barrels for arms of the first class shall not be qualified for proof until they shall be in a fit and proper state for setting up.
Barrels for arms of the third class shall not be qualified for proof until they shall be in a fit and proper state for setting up,
with the proper breeches in; and all barrels lumped for percussioning shall be proved through the nipple hole, with the
proper pins or plugs in.
Barrels for arms of the second and fourth classes:
For provisional proof:—If of plain metal, shall be bored and ground, having plugs attached, with touch-holes drilled in the
plugs, of a diameter not exceeding one-sixteenth of an inch. If any touch-hole shall be enlarged, from any cause whatever,
to a dimension exceeding in diameter one-tenth of an inch, the barrel shall be disqualified for proof. Notches in the plugs
instead of drilled touch-holes shall disqualify for proof. If of twisted metal, they shall be fine-bored, and struck up, with
proving plugs attached, and touch-holes drilled as in the case of plain metal barrels.
For definitive proof:—The barrels, whether of plain or twisted metal, shall be in the finished state, ready for setting up, with
the breeches in the percussioned state, break-offs fitted and locks jointed; the top and bottom ribs shall be rough struck up,
pipes, loops, and stoppers on. All rifle barrels must be rifled; the top and bottom ribs of double barrels shall be struck up,
pipes, loops, and stoppers on, the proper breeches in, and the thread of the screws shall be sufficiently sound and full for
proof.
Barrels for revolving arms of the fifth class shall have the cylinders with the revolving action attached and complete.
Barrels for breech-loading arms of the fifth class shall be subject to provisional proof, according to the class to which they
belong, and to definitive proof when the breech-loading action is attached and complete.
Marks of Proof.
The marks applicable to the definitive proof shall be the proof and view marks now used by the two companies respectively.
The marks applicable to the provisional proof for the Gunmakers Company shall be the letters (G.P.) interlaced in a cypher
surmounted by a lion rampant, and for the Birmingham Company shall be the letters (B.P.) interlaced in a cypher surmounted
by a Crown.

London marks.
Birmingham marks.

Mode of affixing Proof Marks.


On arms of the first and third classes the definitive proof mark and view mark shall be impressed at the breech end of the
barrel, and if the barrel be constructed with a patent breech, the view mark shall be also impressed upon the breech.
On arms of the second, fourth, and fifth classes, the provisional proof mark shall be impressed at the breech end of the
barrel; the definitive proof mark and view mark shall be impressed upon the barrel above the provisional proof mark; and if
the barrel be constructed with a patent breech, or with revolving cylinders or chambers, the view mark shall be also
impressed upon the breech, or upon each of the cylinders or chambers with which the barrel is connected, as the case may
be.
On all barrels the gauge size of the barrel shall be struck, both at the provisional and at the definitive proof.

The Scale following shows the Proportions of Gunpowder applicable under the foregoing Rules and
Regulations to the Proof of the various Classes of Arms as distinguished by the Trade Numbers
indicating the Calibre.

Diameter Charges of Powder for Proof.


Diameter
of Weight
Number of First Class. Second Class. Third Class.
Bore of Balls
of Balls
by for
Gauge. for Definitive Provisional Definitive Definitive
Calcu- Proof.
Proof. Proof. Proof. Proof. Proof.
lation.
inches. inches. grains. grains. ozs. drs. grains. ozs. drs. grains. ozs. drs. grains. ozs. d
1 1·669 1·649 6752 4812 11 ... 4812 11 ... 2406 5 8 3850 8 12
2 1·325 1·305 3342 2324 5 5 2324 5 5 1162 2 101⁄2 1859 4 4
3 1·157 1·107 2211 1531 3 8 1531 3 8 766 1 12 1225 2 12
4 1·052 1·032 1649 1176 2 11 1176 2 11 588 1 5 1⁄2 941 2 2
5 ·976 ·956 1315 930 2 2 930 2 2 465 1 1 744 1 1
6 ·819 ·899 1090 766 1 12 766 1 12 383 ... 14 612 1 6
7 ·873 ·853 931 656 1 8 656 1 8 328 ... 12 525 1 3
8 ·835 ·815 812 602 1 6 602 1 6 301 ... 11 481 1
9 ·803 ·783 720 492 1 2 492 1 2 246 ... 9 394 ... 14
10 ·775 ·755 646 465 1 1 465 1 1 232 ... 8 1⁄2 372 ... 13
11 ·751 ·731 586 437 ... 16 437 ... 16 219 ... 8 350 ... 12
12 ·729 ·709 535 437 ... 16 437 ... 16 219 ... 8 350 ... 12
13 ·710 ·690 493 410 ... 15 410 ... 15 205 ... 7 1⁄2 328 ... 12
14 ·693 ·673 457 383 ... 14 383 ... 14 191 ... 7 306 ... 1
15 ·677 ·657 425 383 ... 14 383 ... 14 191 ... 7 306 ... 1
16 ·662 ·642 399 369 ... 131⁄2 369 ... 131⁄2 185 ... 6 3⁄4 295 ... 10
17 ·649 ·629 374 369 ... 131⁄2 369 ... 131⁄2 185 ... 6 3⁄4 295 ... 10
18 ·637 ·617 352 342 ... 121⁄2 342 ... 121⁄2 171 ... 6 1⁄4 273 ... 10
19 ·626 ·606 334 301 ... 11 301 ... 11 150 ... 5 1⁄2 241 ... 8
20 ·615 ·595 316 273 ... 10 273 ... 10 137 ... 5 219 ... 8
21 ·605 ·585 300 273 ... 10 273 ... 10 137 ... 5 219 ... 8
22 ·596 ·576 287 246 ... 9 246 ... 9 123 ... 4 1⁄2 197 ... 7
23 ·587 ·567 274 246 ... 9 246 ... 9 123 ... 4 1⁄2 197 ... 7
24 ·579 ·559 262 232 ... 8 1⁄2 232 ... 8 1⁄2 116 ... 4 1⁄4 186 ... 6
25 ·571 ·551 251 232 ... 8 1⁄2 232 ... 8 1⁄2 116 ... 4 1⁄4 186 ... 6
26 ·563 ·543 242 232 ... 8 1⁄2 232 ... 8 1⁄2 116 ... 4 1⁄4 186 ... 6
27 ·556 ·536 231 232 ... 8 1⁄2 232 ... 8 1⁄2 116 ... 4 1⁄4 186 ... 6
28 ·550 ·530 223 232 ... 8 1⁄2 232 ... 8 1⁄2 116 ... 4 1⁄4 186 ... 6
29 ·543 ·523 214 205 ... 7 1⁄2 205 ... 7 1⁄2 102 ... 3 3⁄4 164 ... 6
30 ·537 ·517 207 205 ... 7 1⁄2 205 ... 7 1⁄2 102 ... 3 3⁄4 164 ... 6
31 ·531 ·511 — 205 ... 7 1⁄2 205 ... 7 1⁄2 102 ... 3 3⁄4 164 ... 6
32 ·526 ·506 194 205 ... 7 1⁄2 205 ... 7 1⁄2 102 ... 3 3⁄4 164 ... 6
33 ·520 ·500 — 191 ... 7 191 ... 7 96 ... 3 1⁄2 153 ... 5
34 ·515 ·495 182 191 ... 7 191 ... 7 96 ... 3 1⁄2 153 ... 5
35 ·510 ·490 — 191 ... 7 191 ... 7 96 ... 3 1⁄2 153 ... 5
36 ·506 ·486 172 191 ... 7 191 ... 7 96 ... 3 1⁄2 153 ... 5
37 ·501 ·481 — 191 ... 7 191 ... 7 96 ... 3 1⁄2 153 ... 5
38 ·497 ·477 162 178 ... 6 1⁄2 178 ... 6 1⁄2 89 ... 3 1⁄4 142 ... 5
39 ·492 ·472 — 178 ... 6 1⁄2 178 ... 6 1⁄2 89 ... 3 1⁄4 142 ... 5
40 ·488 ·468 154 178 ... 6 1⁄2 178 ... 6 1⁄2 89 ... 3 1⁄4 142 ... 5
41 ·484 ·464 — 164 ... 6 164 ... 6 82 ... 3 131 ... 4
42 ·480 ·460 146 164 ... 6 164 ... 6 82 ... 3 131 ... 4
43 ·476 ·456 — 164 ... 6 164 ... 6 82 ... 3 131 ... 4
44 ·473 ·453 139 164 ... 6 164 ... 6 82 ... 3 131 ... 4
45 ·469 ·449 — 150 ... 5 1⁄2 150 ... 5 1⁄2 75 ... 2 3⁄4 120 ... 4
46 ·466 ·446 133 150 ... 5 1⁄2 150 ... 5 1⁄2 75 ... 2 3⁄4 120 ... 4
47 ·463 ·443 — 150 ... 5 1⁄2 150 ... 5 1⁄2 75 ... 2 3⁄4 120 ... 4
48 ·459 ·439 127 150 ... 5 1⁄2 150 ... 5 1⁄2 75 ... 2 3⁄4 120 ... 4
49 ·456 ·436 — 150 ... 5 1⁄2 150 ... 5 1⁄2 75 ... 2 3⁄4 120 ... 4
50 ·453 ·433 122 150 ... 5 1⁄2 150 ... 5 1⁄2 75 ... 2 3⁄4 120 ... 4

N.B.—Revolving Arms of the Fifth Class shall be proved once only, and such Proof shall be by the Scale laid down for
definitive Proof of the Fourth Class.
As soon as a number of gun barrels are loaded according to the
foregoing scale, they are taken to a house or detached building,
standing apart from other offices. (The woodcut represents the
interior accurately.) The house is lined throughout with thick sheet
iron, and the windows, which resemble Venetian blinds, are
constructed of the same metal. Iron frames are laid the whole length
of the room; on these the barrels of various qualities, when about to
be fired, are placed. In the front of these frames lies a large mass of
sand, to receive the balls. Behind the frame, on which the twist
barrels are fixed, lies another bed of sand; in which, on the recoil,
the barrels are buried. Behind the frame, on which the common
barrels or muskets are tried, a strong iron bar is placed, having a
number of holes large enough to receive the tang of the breech, but
not the barrel. The barrels being thus fixed, it is impossible for them
to fly back. A groove runs along the whole length of each frame, in
which the train of powder is strewed to ignite the charges, upon
which the barrels are laid, with the touch-holes downwards.
When everything is ready for the proof, the windows are let close
down, the door is shut and secured, and an iron rod heated red hot
is introduced through a hole in the wall. On igniting the train, a
tremendous explosion takes place. The windows are then drawn up,
the door opened, and the smoke dissipated. The twist barrels are
found buried in the sand, the common ones are thrown forwards;
some are found perfect, others burst to pieces. It is rarely that best
barrels are found burst; more frequently they are bulged, or swelled
out, in places which are faulty, or of a softer temper. Those that are
found perfect, are then marked with the provisional punch of
different sizes (but having the same impression), according to the
quality of the barrel. In London and Birmingham they have now an
additional punch, containing the number of the bore by which the
barrel has been tried. This mark easily enables the observer to
discover whether the barrel has had any considerable quantity bored
out after proving. Those that are bulged are sent to the maker, who
beats down the swellings, and sends back the barrels to be proved
again. They generally stand the second proof, though we have
known a barrel undergo four proofs before it was marked. The
common barrels are required to stand twenty-four hours before they
are examined; when, if not burst, any holes or other material
imperfections are made quite apparent by the action of the
saltpetre. Such barrels are, of course, sent back unmarked. Those
that are found satisfactory are duly stamped and taken home.
The importance of the gun trade to England may be estimated from
the number of barrels proved during the last year, 1857, of which the
following is a correct statement:—

Provisional Proof.

Plain iron barrels 185,776


Twisted barrels 136,804
Saddle pistol barrels 33,480
Best pistol barrels 962
Common pistol barrels 2,066
Revolving and double barrel pistols 57,106
Total 416,194
Definitively proved, 70,100, being principally double barrels.

This is in Birmingham alone; no doubt the London Company prove to


the extent of 200,000 yearly, which may also be debited to
Birmingham, as the barrels are all welded, bored, and ground before
being sent to London. In addition to these may be counted the
Government contracts of some hundred thousands yearly.
The passing of this Act of Parliament levelled all distinctions between
London and Birmingham proved barrels; they are now treated
precisely alike, and one is equally good with the other.
CHAPTER VII.
THE SCIENCE OF GUNNERY.

“Science begins at the point where mind dominates matter, where the attempt is
made to subject the mass of experience to the scrutiny of reason. Science is mind
brought into connection with nature.”—Cosmos.

A new era in the science of gunnery may be dated from the


commencement of the latter half of the nineteenth century; and long
before its close other improvements may be effected which shall
eclipse even those of our day. A new elementary principle has been
infused into the science. Rifles are now really weapons of the
highest order; in truth we may be said to have only recently become
acquainted with the principles on which they should be constructed.
Little of science had hitherto been applied to them; as military arms
they were neglected for centuries, to be ushered into notice at last
by the unassisted efforts of private individuals; Government, to
whom arms were of the greatest importance, having systematically
neglected all improvement, by invariably refusing pecuniary aid, the
only grease at all calculated to overcome the friction retarding the
wheels of progress. It is an old proverb, that “one extreme begets
another,” and when changes are once started, the difficulty is to stop
them; the tendency is to rush on from one alteration to another,
before we are really well acquainted with what we have so hastily
thrown aside. Improvement does not always follow a change; the
human race, and the English more especially, have an inordinate
desire for “the marvellous;” and multitudes of “wonderful
discoveries” and inventions of the utmost value are heralded daily by
the ever eager press, often to be as hastily forgotten, or discovered,
even by their promulgators, to be myths.
Improvement, to be at all beneficial, must bring with it all the
elements of improvement; and to render it easy of attainment, none
of its essential points should be costly. In gunnery more especially, it
is essential to avoid all unnecessary friction, excess of recoil, and
waste of gunpowder; whilst, at the same time, transport of the gun
must not be cumbersome, and durability in all its points is essential.
How few study the subject in all its bearings! How rapidly
conclusions are jumped at! Even in getting range, if it is to be
purchased at the cost of other essential principles, it is not economy
to sacrifice several even moderately valuable principles for the sake
of range alone. The experience of the present age has shown that all
our important discoveries have their limits: the locomotive cannot be
used with advantage beyond a certain limited speed; steam vessels
attempted to be propelled at an unusual velocity have but a very
brief endurance, and rapidly decay. All matter has power only to
effect a certain amount of work, and this is endured best at a
medium application; showing most clearly that “the race is not
always to the swift or the battle to the strong.”
Experience is required in the greatest of modern inventions.
Electricity, at a moderate immersion, subjected to a moderate
superincumbent weight, is an effectual messenger, swift as thought;
but when overweighted by immersion to depths where the
superincumbent pressure amounts to thousands of pounds upon the
square inch, then the messenger becomes paralysed, and refuses to
obey man’s will; showing very clearly that until that pressure be
artificially removed by insulating the conducting wire in tubes equal
to restrain or keep from it that enormous load, the lasting success of
an Atlantic telegraph is very doubtful. Many similar instances might
be cited to show the necessity of considering well the established
laws of nature, and their bearing on the object pursued. In no
science is this of more importance than in gunnery; and the
hundreds of useless inventions in gunnery are to be ascribed to the
non-observance of these rules. The two-grooved rifle, the “steam
gun,” “the sciva,” “Warner’s long-range myth,” and many other
inventions equally absurd, engage the attention for a time, but soon
vanish: in fact, all experience shows that improvement can only be
effected in accordance with certain established principles of nature
and practical science.
Iron, in quantities sufficient for all reasonable requirements, is a
dutiful servant; but, when required of colossal proportions, it refuses
to obey: giving us a hint from nature, that we should be content
with moderation.
All the principles appertaining to science are based on certain
established laws; the unsoundness of one renders the superstructure
unsound also; and any deductions drawn from unsound principles
are comparatively worthless. Gunnery, as a science, must be in
uniformity with truth in all its parts, or no science exists in its
arrangements. This will be best illustrated by dividing the subject
into several heads: 1st, the explosive power and its velocity; 2nd,
the retarding agents, air and friction; 3rd, the construction of the
projectile tubes; and 4th, the form of projectile best calculated to
attain a perfect result.
1st. The explosive power. Gunpowder has been stated by different
authorities to liberate its gases with very different degrees of
rapidity. Hutton has given to it a much greater rapidity than Robins
has evidently even surmised; though, no doubt, as we have already
shown, high velocity in gunpowder depends on several
circumstances—the degree of purification of its ingredients, their
intimate mechanical mixture (that the elements may exert their
affinities with the utmost facility), and, lastly, the degree of
granulation observed: and in addition, the suitability of the tubes or
vessels for carrying on correctly such important experiments. Robins
and Hutton unquestionably may be regarded as the English, if not
the European, authorities, and any work on the science of gunnery
would be very incomplete without their valuable elucidations.
Previously to the researches of Robins, the theory of atmospheric
resistance was but imperfectly surmised, and when he made his
statements of the immense resistance which the fluidity of the air
offered to projectiles in a high state of velocity, they were treated as
the idle chimeras of a speculative brain; and yet he only was enabled
to estimate the real effect of the explosive nature and force of
gunpowder to a very limited extent: indeed, so limited, that Hutton,
only twenty years subsequently, speaking of Robins’ theory, says,
“Mr. Robins and other authors, it may be said, have only guessed at,
rather than determined. That ingenious philosopher, in a simple
experiment, truly showed that, by the firing of a parcel of
gunpowder, a quantity of elastic air was disengaged; which, when
confined in the space only occupied by the powder before it was
fired, was found to be nearly 250 times stronger than the weight or
elasticity of the common air. He then heated the same parcel of air
to the degree of red hot iron, and found it in that temperature to be
about four times as strong as before; whence he inferred, that the
first strength of the inflamed fluid must be nearly 1,000 times the
pressure of the atmosphere. But this was merely guessing at the
degree of heat in the inflamed fluid, and, consequently, of its first
strength; both which in fact are found to be much greater. It is true
that this assumed degree of strength accorded pretty well with that
author’s experiments; but this seeming agreement, it might easily be
shown, could only be owing to the inaccuracy of his own further
experiments; and, in fact, with far better opportunities than fell to
the lot of Mr. Robins, we have shown that inflamed gunpowder is
about double the strength that he has assigned to it, and that it
expands itself with the velocity of about 5,000 feet per second.” On
the same subject he further says:—“On this principle it was that Mr.
Robins made all his experiments and performed all his calculations in
gunnery. But it is manifest that this method of guessing at the
degree of heat of the flame must be very uncertain and
unsatisfactory, being much below the truth; since all our notions and
experience of the heat of inflamed powder convince us that it is
higher than that of red hot iron, and, indeed, it has clearly appeared
from our experiments, that its heat is at least double that of red hot
iron, and that it increases the elasticity of the elastic fluid more than
eight times.”
Here is evidence, though not conclusive, of the immense force of
gunpowder, and also of the progress of knowledge on the subject;
yet it clearly shows the evil of coming to hasty conclusions, however
well supported by apparent facts, as it has had in this case a
tendency to check inquiry and retard the advancement of
knowledge. For the extensive experiments of Hutton were but
limited in discovery, because they were not carried to a sufficient
extent, and thus, they are quite unsuited to the present day. He was
satisfied because he had gone further than any of his predecessors;
and though he established and clearly proved the soundness of his
own theory, yet he could not either view the subject to its utmost
bounds, nor yet go sufficiently far, but that others, taking up the
question where he left it, may pursue the subject to a much more
remote limit. The subject, indeed, was limited to him. He far excelled
Robins, no doubt, as he has shown; but that involves no detraction
from the merit due to Robins for his experiments and discoveries, no
more than any individual proving the subject to be a more extensive
one than Hutton did, would excel Hutton; for the value of
improvement is more to be attributed to him who lays the
foundation, than to him who raises the building. So is it in this case;
Robins laid the foundation for an extensive knowledge of the nature
and power of the explosive fluids, and Hutton built upon that
foundation a certain extent of superstructure, and there he left it,
without roofing the building: he considered the question as settled.
Common consent has, as yet, received his conclusion as unshaken
and uncontroverted; and it is not my intention to make the attempt
to controvert it, but merely to show that his deductions fall short of
what the principles of gunpowder-making admit—carried out in the
more extensive way it has been within the last few years—owing to
the limited nature of his experiments. This is rather an extensive
position for me to occupy, or endeavour to hold: but I do not mean
the size of the tools of experiment so much as the diversity of them;
for exploding ten thousand tons of powder in the same machine and
in the same way, would but give the same or similar results; it is the
variety and the singularity of experiments that expand and increase
the fund of knowledge, and enable the mind to conceive and
comprehend the immensity of the power and velocity of this
wonderful combination. We have been principally indebted to the
exertions of the chemist for means of purifying and extracting from
the ingredients which form this astonishing compound force, the
impurities and foreign substances which exist, to a certain extent, in
all the three, and thus tending to form a more perfect combustion by
increasing the affinities.
Hutton shows that gunpowder is but so much condensed air; for he
says “We may hence, also, deduce the amazing degree of
condensation of the elastic air in the nitre and gunpowder, and the
astonishing force experienced by its explosion. It has been found by
Mr. Robins, and other philosophers, that 3-10ths of the mass of the
powder consists of the pure condensed air, or that the weight of the
condensed air is equal to 3-10ths of the whole composition. But the
whole composition of the powder consists of eight parts by weight,
of which six parts are nitre, one part sulphur, one charcoal; of which
the nitre or 3-4ths of the composition furnishes the whole of the
condensed air, while the sulphur and charcoal only give the fire that
produces the explosion. But 3-10ths of the whole mass of eight parts
is equal to 4-10ths of the six parts of nitre, that is 4-10ths or 2-5ths
of the nitre consists of condensed air, or the weight of the gross
matter in the nitre as four to six, or as two to three; and these two
parts, it is probable, are of equal density or specific gravity. Yet the
specific gravity of nitre is 1,900, that of water being 1,000, and of air
1·2, which is contained in 1,900, as much as 1,583 times; that is,
the air in the nitre must be condensed the amazing quantity of 1,583
times, if its specific gravity be equal to the compound nitre itself.”
Also, “The air is condensed in the nitre about 1,600 times, nearly
double the density of water, which may well be considered as
probably the greatest degree of compression that air is capable of.
Hence it may be perceived that a prodigious force must be exerted
by nature in generating nitre; and as this great force actually exists
in nature, it is very probable that the air in the nitre is thus
compressed into the most dense state possible, and in this consists
the similitude among the different particles of nitre.”
This extract from Hutton enables us to divest the question of any
technicalities, and puts it in so plain a garb that the simplest mind
may comprehend it. Now, the great improvement of chemistry has
been to extract from the nitre the gross material which is contained
in the proportions—2-5ths impurities, and 2-5ths condensed air;
thus, half the quantity being useless, the extraction of these alloys
gives a greater quantity of condensed gases in the same quantity of
matter; for if we take away 2-5ths of the proportions of useless
matter, and supply its place with 2-5ths more condensed air, we thus
get 4-5th explosive matter in the same bulk of material, and thus
simply obtain an immense increase of power without an increase in
bulk. We have here evidence of the progress that has been made in
the science of explosive force.
Considering the difference between gunpowder in 1783 and
gunpowder in 1858, I cannot say, with Hutton, that the force is
doubled now to what it was when he wrote; but I believe that this
would not be far from the truth; for it must be quite clear—if he is
correct (which I believe he is) in saying the force of gunpowder
consists in the quantity of explosive matter let loose and expanded
by heat—that the greater the quantity of condensed matter we may
have in any given weight, the greater the force, and the more rapid
the explosion: purified saltpetre thus forming nearly pure gaseous
matter; as the diamond is pure carbon. It seems singular, and is
rather presumptuous to say, that Hutton was not much of a chemist;
but had he been more so, he must have perceived that in the
extraction of the foreign matter from the nitre, existed the means of
obtaining an increased quantity of explosive power, and a
proportionate increase of speed or velocity in that explosive material.
To ascertain the velocity best suited to all projectiles, constitutes the
germ of the science; and that we are approaching a new era in even
that more intimate portion of the science, is daily apparent. Science
shows clearly that if a given force, a quantity to be correctly
ascertained, can produce a certain result, the use of more is waste,
and unworthy of the seeker after perfection; and thus we have to
determine upon, or define, what is the degree or size of gun for
certain effects: a mere calculation nearly allied to that portion of
engineering which would define what power of engine would work a
thousand cotton spindles, or raise a million gallons of water; and all
this will eventually be done. Science requires that there should be no
excess, no waste, no unnecessary recoil, and all that combined with
the utmost range of projectile; this will have to be defined accurately
before we can clearly or truly say we are masters of the science of
gunpowder. True it is that the granulation of gunpowder gives a clear
road to its attainment; but it will be a wearisome journey to reach
the summit: yet it must and will be effected, and the nation that first
attempts and carries out the attainment, will evince a real love for
and mastery of science.
The following practical experiments illustrate the degree of velocity
and the effects of projectiles so clearly, that they alone will convey
some idea of the high velocity of the evolutions of the gases in
gunpowder.
My experiments are, like Robins’, on a small scale; nor would I, like
Hutton, try a brass gun of sixty calibres in length, carrying a one-
pound ball; for one is strictly more limited than the other, and thus
rendered the results laid down by him imperfect: for, as he says, “If
you fill the tube with powder you get no greater velocity, as there is
not a duration in the confinement to enable the powder to explode.”
If he had assimilated the grain of his powder to the gun, he would
have obtained a different result; and a knowledge of this fact, I
apprehend, makes all the difference. The greatest velocity he
obtained was with powder 11⁄2 times the weight of the ball in a gun
of sixty calibres in length, and the velocity he then obtained was
only 3,181 feet per second. The inferences that probably induced
him to recommend others not to endeavour to obtain a greater
velocity than 2,000 feet per second, were, like these experiments,
drawn from imperfect data. With a ball of an ounce weight in a
barrel of sixty calibres, and with 3-4ths the weight of ball in powder,
or 12 drachms, a velocity can be given to the ball to equal it in force
to 46,875 pounds. The velocity of this ball I leave to the calculations
of the mathematical world. But, however, I will give the results of a
round of experiments tried to ascertain this; and if the data laid
down be correct, that the velocity of a ball must be multiplied by its
weight to find the force, the result will be the establishment of a
system of velocity never yet dreamt of. I cannot but imagine that
there exists some error; though where it is I know not: every
deduction I have drawn is consequent upon the results hereafter
described.
“The power required to force a punch 0·50 inch diameter through an
iron plate 0·08 inch thick is 6,025 pounds, through copper 3,938
pounds. A simple rule for determining the force required for
punching may thus be deduced:—
“Taking one inch diameter and one inch in thickness as the units of
calculation it is shown that 150,000 is the constant number for
wrought-iron plates, and 96,000 for copper plates.
“Multiply the constant number by the given diameter in inches, the
product is the pressure in pounds which will be required to punch a
hole of a given diameter through a plate of a given thickness.”
Now an idea struck me, that this would form a very good test of the
comparative force of gunpowder, and I consequently commenced an
extensive round of experiments.
In the first attempt I found the results to vary with the weight of the
pendulum of iron plate, and that it was necessary to obtain
uniformity of size and surface; as it must be comprehended that the
only resisting medium to the pendulous plate was atmospheric
resistance, and a dissimilarity of size of surface would invariably give
different results. Having a number of plates of the different
thicknesses hereafter described, I continued increasing the charge
from a definite quantity, until the projectile was driven with sufficient
velocity to perforate the plate suspended. The gun selected for this
purpose was of heavy material, weighing nearly seventeen pounds,
it was three feet long, the metal of the barrel as thick at the muzzle
as at the breech, and carried a spherical ball of sixteen to the pound,
or one ounce, and which fitted tight with the thinnest patch
procurable. The bore was perfectly cylindrical, and plain inside, being
polished longitudinally to a high state of fineness. With a charge of
twelve drachms of Curtis and Harvey’s diamond grain powder, the
ball went through the half-inch plate, but went only a few yards
further; denoting that the effort necessary had nearly exhausted its
velocity and momentum.
The recoil of the gun was of the most severe description, and the
shoulder had to be protected for many explosions previous to this
high charge. The larger sized grain was insufficient, ten drachms
effecting the greatest extent of power it seemed capable of, and it
became quite apparent that the tube would not explode more
powder, as indications convinced me: when any more was added, a
portion came out unburnt.
The force necessary to effect this, by the above calculation, is
46,795 pounds.
The next plate was 7-16ths thick, and a charge of ten drachms
punched the piece out clean; nine and a half drachms were equal to
it, when the centre of the pendulum could be hit fairly, because
there was then an equal resistance from the atmosphere, which
cannot exist in cases where the edge of the disc receives the blow.
I got with ease a perforation in a 6-16ths plate, with a charge of
either fine or coarse powder, not exceeding eight drachms; a charge
of seven drachms of fine grain was unequal to the task; but seven
drachms of the coarse showed evidently greater effects produced,
though the perforation was not perfect. Six and a half drachms of
No. 2 grain penetrated a plate of 5-16ths thick easily, while it took
full six and three-quarters drachms of fine grain; five drachms of the
larger perforated a quarter-inch plate, but it took full five and a half
drachms of fine grain to effect the same; while a 3-16ths plate took
three and three-quarters drachms of fine, or three and a quarter of
No. 2 grain; and 1-8th plate was easily punched by a charge of two
and a half drachms coarse or three drachms fine. I will place the
relative results in a table, with the force effected by each:—

Punched a Equal in
Oz. Drachms. boiler plate force to
1 ball 12 of powder Half-inch thick 46,875 lbs.
1 „ 10 „ 7-16ths „ 41,015 „
1 „ 8 „ 6-16ths „ 35,155 „
1 „ 1
6 ⁄2 „ 5-16ths „ 29,295 „
1 „ 5 „ 4-16ths „ 23,437 „
1 „ 3 1⁄4 „ 3-16ths „ 17,578 „
1 „ 2 „ 2-16ths „ 11,718 „

Were I to adopt the established method of calculation, multiplying


the weight of ball by the velocity, I should get an answer that would
point to the utter impossibility of any such velocity being possible.
And yet the result is, according to the rule of figures, correct; but in
truth there are exceptions to many rules, for they are only correct
when applied to known products.
That the velocity of these balls was much, very much, greater than
7,000 feet per second of time, there cannot be any doubt; it was
nearly three times that. Yet I must not conceal the fact, that this
punching is the more perfect, the higher the velocity; and it shows
how the fibres of iron are separated from a want of vibration to
equilibrise the cohesion. Mr. Colthurst found that duration of
pressure lessened the ultimate force necessary to punch through
metal, and thus it may be that extremely quick pressure may
produce the same. Therefore I suspect it is not the most correct
theory that calculates force to be accomplished at all times by
extreme velocity; there will be found discrepancies in the rule, and
one of them arises from no calculation ever having been made with
extreme velocities: medium velocities may generally give such
conclusions, but the very extreme in this case can never have been
taken into consideration at all; as I have very little doubt—in fact, I
am certain—that no person ever obtained such high velocity before.
It must, and is a vast deal greater, incomprehensibly greater, than
any velocity obtained by Hutton; and much more extensive than
ever could be obtained, or, in fact, ever will, by any ordnance
whatever. I wish much I could have experimented with a gun of
greater length and bore, for with one in every way fitted for the
purpose, I have no doubt of being able to perforate an inch
thickness of plate.
Should any person possessing the opportunity and means, wish to
try the experiment, I would advise them to get a barrel of 41⁄2 feet
long, 8 bore, to carry a 2 oz. ball, and of a weight to allow of
extending the explosion up to 30 drs. of powder; they would then
obtain the extent of force I have suggested. There is a certain point
to be strictly observed: see that the plate you use is perfectly sound;
for if laminated, or composed of various plates not firmly welded and
attached, the experiment would be imperfect, as there would be an
uneven vibration created, and acting as the hammer does when held
against the point of the nail while driving it in, clinches the point, so
does the substance in the portions of plate prevent a perforation. An
ounce ball, suspended against the back of the pendulum, by the jar
or blow it receives and communicates, completely prevents the
effect, and the ball is flattened, instead of perforating the object
struck: so is it if you place a 1⁄4-inch plate against any support; it
thus has the power of perfectly resisting the force of the ball, though
fired with considerably more power than is requisite under other
circumstances. The effect appears to be chiefly mechanical; the
outer fibres are driven in upon those behind them with such
quickness that they lose cohesion, or are condensed quicker than
the waves of vibration travel, thus giving them no means of
communicating the vibration. But when punched, the rapidity of their
motion produces in the metal a sound of the most intense vivacity,
which plays upon the ear for a considerable period, with rather a
pleasant effect. Lead alone is capable of being used in this
experiment; except, of course, the precious metals, which it would
not be convenient to use. Even an adulteration of the slightest
quantity of solder is sufficient to prevent the result which lead, pure,
will invariably give. Lead projected against lead, if sufficiently thick,
cannot perforate, but the lesser portion becomes flattened; a cast-
iron ball fired against lead, with a certain velocity, is broken into
pieces, affecting the lead comparatively little: showing beautifully the
peculiarity of dense incompressible bodies to resist most effectually
the greater the velocity with which they are struck. Water will, if
struck very sharply with the flat of a sword, act against the blow in a
way to splinter the blade into pieces. The greater the velocity with
which a ball is fired into water, the less the depth of penetration;
thus showing clearly the many excellent properties of dense
incompressible bodies as projectiles, and proving the objection that
lead is too soft for artillery to be without a foundation, and only
entertained from a want of knowledge of its nature.
A point of great importance was exemplified during these
experiments; and as the question has lately given rise to
considerable discussion, it will be well that the facts should be
stated.
At very short distances from the muzzle of the gun the penetration
was found to be less than at distances more extended. At five yards
the iron plate could not be perforated; at ten yards the effect was
much greater, but fifteen yards was the least distance at which it
could be said to be effectually perforated; at twenty yards the result
was still more satisfactory, clearly demonstrating that bullets gain
both in velocity and penetration for a considerable distance after
leaving the muzzle of the gun. The following experiments verify this
remark:—
In the report of the experiments which were carried on at Cork in
1852, it is stated that the power of penetration of an elongated rifle
bullet gradually increases as the range is increased, up to 190 yards.
In order to prove this, experiments were carried on at Enfield for
three days with a variety of fire-arms, and different sorts of
projectiles. On the fourth day the experiments were repeated with
the common musket and Wilkinson’s rifle. The former, at forty yards,
gave a penetration of 2·25 inches; and the latter averaged 2·75, in a
target of green elm. Again: at ninety yards, the musket penetrated
2·25 inches, and the rifle 3·5 inches. At 120 yards, the musket gave
2·5 inches, and the rifle 3·25. Both being subsequently fired at every
successive ten yards up to 220, the result was that the penetration
of the musket ball gradually decreased in power as the distance
increased, while the elongated bullet gained power of penetration up
to 190 yards; after which it slightly decreased.
2nd. Consequent on the velocity of the explosive fluids is the
resistance of that aëriform fluid filling all space. It has been
calculated that in a vacuum, matter in motion would be a long time
in coming to rest; and very providentially it is that nature in her
grand arrangements has made one element to control another. In no
other portion of nature’s work has anything more wonderful than
atmospheric air been produced; its action on the velocity of
projectiles is of so extensive a nature, that without clearly
understanding that action, the science of gunnery never can be
thoroughly acquired. The resistance of the atmosphere is in
proportion to the velocity of the attempt to displace it; the higher
that velocity becomes, the greater is the resistance. This is shown by
the actions of all the fulminates. A quantity of the fulminate of silver
exploded on a copper plate will perforate that plate, or, if fired upon
a piece of wood, will bury itself in that substance, splintering it in
proportion to the quantity. Now, ordinary gunpowder has no such
effect as this, because, though it may produce the same amount of
expansive gas, it produces it at one-fourth the velocity of the
fulminates: the air is driven back upon itself so gradually as to offer
no very important resistance; but the action of the fulminates is so
rapid and so violent that the high elasticity of the air has not time to
yield, and the force is driven into the apparently more solid material,
the copper or the wood.
The mode in which atmospheric resistance mostly interferes with
projectile force is owing to the columnar form it assumes in the
tubes of all descriptions of gunnery. If the velocity of gunpowder be
as great as we suppose it to be, the displacement of a column of air
must be effected by driving the whole column in a gun-barrel of
many inches, into a column probably less than half an inch in height;
or, if the length of the tube from the starting of the charge to the
muzzle be 38 inches, then will the displacement require a force
capable of condensing thirty-eight atmospheres into one, or
something like 570 lbs.; without estimating the lateral pressure of
that column on the sides of the gun-barrel, which may be safely
estimated at one-half more. It may be supposed that the column
would be partially in motion for a greater distance than half an inch
in front of the projectile; but this is disproved by the fact that time is
essential to put aëriform matter in motion, and naturally it never
does so at a greater velocity than it is familiarly known to do in the
shape of winds: but the fact is better illustrated by the frequent
bursting of barrels near the muzzle, caused by a piece of snow or
clay, a piece of paper or wadding. Were a current established around
this projection it would pass on, but the air strikes these light
obstructions when in a high state of condensation, amounting to
many atmospheres in one: so many as to be nearly equal to a solid
which is more powerful than the barrel; the latter therefore
succumbs to it.
The resistance of the air is so highly philosophical a question, that I
merely touch on its actual bearings on the passage of projectiles to
show how the quantity of force is absorbed or expended in relation
to the quantity of the gunpowder employed; which, it may be
assumed, is a proportion of nearly one-third of the whole, or a
quantity independent of that necessary to give velocity to the leaden
projectile, to enable it to overcome the still and uniform impeding
agent up to the end of its flight. The rapid exit of the bullet from the
barrel, with a resisting influence of this weight into the
comparatively insignificant one of 15 lbs. to the square inch, will fully
explain how it is that a bullet increases in velocity even up to a
considerable distance after leaving the muzzle of the gun; and
further showing that in all arrangements of truly scientific gunnery,
the increasing resistance must be met by a fresh production of
explosive fluid over every atom of space in that tube, where it is
demonstrable that the resistance is increasing in a geometrical
progression as the point of exit is becoming nearer; so that gunnery,
unless all the contingencies are provided for, must necessarily
remain an imperfect science.
Intimately allied to the displacement of the atmosphere is the
amount of friction. Gunnery is now rid of the anomaly of being
assisted by friction: the detention of the projectile in the tube by
artificial friction, to enable more force to be generated, is one of
those absurdities pardonable only in bygone days. Science is best
consulted by lessening friction; guns of steel, with interiors as fine as
the polish in a mirror, are found to shoot best: a rough road is but so
much force uselessly absorbed; the experience of the last few years
having proved that a range of 1,800 yards cannot be accomplished
except with barrels having surfaces as smooth as possible.
Rifles, no doubt, are now in use in which, by increasing the degree
of spiral, friction is more than doubled, perhaps trebled; but such
unscientific constructions are but as one error to counteract another.
Unscientifically formed projectiles not having in themselves the
principles necessary for true flight, have to receive a counteracting
agency in the shape of additional spinning, on an axis coincident to
the line of flight, to enable them to range a given distance, with, as
it will be perceived, an additional amount of expellant agency; but
these cannot be included in the category of scientific gunnery.
3rd. Next to absence of friction is the construction of the gun barrel.
Already have we shown that the inner surface of a gun barrel
requires to be like glass; next to this it is necessary that the metal
should be composed of the most unyielding structure. Metals absorb
force in proportion to their softness: a barrel constructed of lead
gives the worst result of any metal; in truth, as is the increase of
tenacity and density in the tube, so is the increase of range in
projectiles. The wonderful results displayed by the use of steel guns
of all descriptions bear out this assertion to the fullest extent. A
yielding gun barrel may be compared to the dragging of a heavily
loaded waggon over boggy ground, which rises in a wave before the
wheels during its progress.
4th. Next in importance to the inflexibility of the gun barrel is the
form of projectile best calculated to displace the atmosphere during
its extended flight. Under the head of Rifles this subject will be more
fully discussed; but, as thousands of years have stamped the arrow
as being in accordance with nature’s laws, it should no doubt be the
object of science to approximate the leaden projectile to that form
as much as possible, and hence the cylindro-conoidal may be
assumed to be the best form of projectile.
That both Jacob’s and Whitworth’s bullets partake of a certain
amount of “wabbling” motion after leading the muzzle of the gun is
certain, from their length, as well as from the fact that in both the
centre of gravity is in the hinder part of the bullet; thus they are
both in reality bad in a scientific point of view.
If any merit can be claimed for either, it is on account of the
mechanical ingenuity displayed in neutralizing the effects of want of
scientific principle. The want of principle, however, is not the only
evil, were such guns to come into general use; their manufacture, in
the hands of that portion of the gun trade which never estimates
consequences, and never studies the theory of the science at all, but
manufactures all fire-arms by “rule of thumb,” would prove
dangerous in the extreme.
The bursting of barrels in any attempt to project lengthened
projectiles is of a very different description to that which ordinarily
occurs, on account of the different direction in which the force is
applied. In consequence of their greater length, and their increased
friction against the sides of the barrel, they are more reluctantly set
in motion—i. e., their inertia is with greater difficulty overcome. The
result of this is, that in overcoming their inertia the greatest strain is
exerted backward, on the breech of the gun; which, if not more firm
than usual, is blown out, entering the forehead of the shooter: an
accident which would prove fatal not only to the gun, but to the
person who used it.
This accident may no doubt be effectually guarded against by
strengthening the breech end of the gun as well as the breech itself;
but without that precaution it is to be feared that such accidents
would be of frequent occurrence.
A considerable error may easily be promulgated, as to the heat
necessary to be applied ere gunpowder will explode. A late writer
says, it is necessary to raise it to 600 degrees before it is explosive.
This is a splitting of hairs, and such a palpable mystification, that it is
scarcely worth noticing. But I will explain: if you place upon a plate a
few grains of powder, by heating the plate underneath (for instance,
on a smith’s fire,) you will see the sulphur giving out a blue flame, it
being easily fused. As the plate becomes heated to nearly a red
heat, the whole explodes, in consequence of the charcoal and nitre
not being hot enough to allow the gases generating the heat to be
liberated; but as soon as this does take place the explosion ensues.
Now, it is a well known fact, that the smallest particle of matter
possessing above 600° of heat, will ignite any quantity of powder it
comes in immediate contact with; we will suppose with one portion
of charcoal, one of sulphur, and one of nitre (it matters not how
small they are: a ten hundredth part of the substance of one of the
smallest grains of powder would suffice), and if it has the means of
communicating to these small portions 600°, this is sufficient, as
their explosion induces also that of the very largest quantity: for it
ought to be perfectly understood, that a great explosion is but so
many millions of small ones combined, and by their united force
effecting the great results we see. The ingredients of powder are
ground and intimately mixed together on the bed of the mill to the
great extent they are, to the end that, if possible, there shall not be
in the composition two grains or portions of one ingredient in
immediate contact with each other; but that, when the ignition does
take place, each may be present to add its peculiar gas, in order that
each affinity may be supplied. Thus becomes evident the necessity
of a most extensive incorporation, a blending and equal division of
mixture throughout the whole material.
The advantage of unglazed gunpowder is here fully shown; for it
presents an inequality, a roughness of surface, over which the flame
from the percussion mixture cannot travel without igniting some of
the prominent parts, and thus the whole. You may glaze powder and
make it so smooth that it would be very difficult indeed to ignite; but
except that it enables the powder to resist moisture better, it is
otherwise very detrimental, as tending both to prevent ignition and
lengthening the period of effecting it.
The flame from the percussion powder is of that intense and vivid
description, that if a charge of powder in the breech of a gun is
loose, the flame will form a mass of condensed air round itself, and
driving the grains of powder before it, prevent the immediate
contact of the heat and the particles of powder, until the heat is
expended; and thus arises a “miss fire.” If the powder is up only to
the nipple, there being a quantity of air in the tube of that nipple,
the explosion of the fluid will drive down this air, and condense it
between the powder and top of the nipple to such an extent as to
cause a certain “miss fire.” It becomes requisite to find a remedy for
this, and it can only be done by bringing the powder into the very
vicinity of the explosion on the nipple. This can be effected in several
ways, but the most perfect is to obtain as direct a communication as
possible; a widening of the perforations of the breech, and space to
allow the powder free access up the nipple. For this purpose we
propose an improved form of nipple. The centre one of the three
(here shown in section) is considerably broader and shorter than the
others. A cap made broader and not so deep would be an
improvement, as bringing the point of ignition nearer the charge,
and thus effecting a saving of time; for great and wonderfully quick
as is the explosion, it is clear to the senses that it may be quickened.
We are not finding fault with the “lightning being too slow,” as
Colonel Hawker says; but science means perfection, and the nearer
we can come to it the better.
OLD PLAN OF NEWEST PLAN OF IMPROVED NIPPLE
NIPPLE. NIPPLE. OF 1835.

The nipples now in general use have the smaller orifice at the
bottom, and, being lined with platina, never foul. Experience has
shown that admitting the gunpowder into the nipple “is not
advantageous,” especially with large grained powder; by
constructing the nipple with the small orifice at the bottom, the
largest grain can be used beneficially. As the velocity of the
fulminating gas is much greater than “a train” of gunpowder ever
can be, quickness is also gained by their adoption. I have used them
for many years with great success; nothing but cost deters their
general adoption. The passing of the flame through the very small
opening in the platina, by this very high impingement, increases its
heat to a great extent, ensuring explosion.
The true science of gunnery consists in knowing that a certain force
is requisite to effect a certain purpose, or, in other words, to kill at a
certain distance; and also how to arrange that force so as to effect
the purpose without having any extra force, or any waste of powder,
nor yet too little, but with a corresponding result: a sufficiency;
neither more nor less. This we have shown is attainable by the
mechanical arrangement of granulation; for it is useless to use less,
or to use an iota more of fine grain powder, if the size larger will
effect the purpose without that iota. Propellant velocity is the grand
desideratum in all gunnery; the obtainment of this, to the greatest
extent, is the power of killing at the greatest distance: all ranges are
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like