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

AndroidLabManualforNoviceVolI

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

AndroidLabManualforNoviceVolI

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

Android Lab Manual

for Novice – Vol I


i
Evincepub Publishing
Nehru Nagar, Bilaspur, Chhattisgarh 495001
First Published by Evincepub Publishing 2019
Copyright © Dr. Poornima G. Naik 2019
All Rights Reserved.
ISBN: 978-93-89482-20-1
Ebook Price: 500 ₹
This book has been published with all reasonable efforts taken to make
the material error-free after the consent of the author. No part of this
book shall be used, reproduced in any manner whatsoever without
written permission from the author, except in the case of brief quotations
embodied in critical articles and reviews. The Author of this book is
solely responsible and liable for its content including but not limited to
the views, representations, descriptions, statements, information,
opinions and references [“Content”]. The Content of this book shall not
constitute or be construed or deemed to reflect the opinion or expression
of the Publisher or Editor. Neither the Publisher nor Editor endorse or
approve the Content of this book or guarantee the reliability, accuracy or
completeness of the Content published herein and do not make any
representations or warranties of any kind, express or implied, including
but not limited to the implied warranties of merchantability, fitness for a
particular purpose. The Publisher and Editor shall not be liable
whatsoever for any errors, omissions, whether such errors or omissions
result from negligence, accident, or any other cause or claims for loss or
damages of any kind, including without limitation, indirect or
consequential loss or damage arising out of use, inability to use, or about
the reliability, accuracy or sufficiency of the information contained in
this book.

ii
Android Lab Manual for Novice – Vol I

By

Dr. Poornima G. Naik


Dr. Girish R. Naik

iii
Android Lab Manual for Novice

Acknowledgements

Many individuals share credit for this book’s preparation. We extend our sincere thanks to Late Prof.
A.D.Shinde, the Founder Director and Managing Trustee who has been a constant source of inspiration
for us throughout our career. His support is really a driving force for us. Also, we would like to thank
Dr.R.A.Shinde, Hon’ble Secretary, CSIBER, Kolhapur for his whole hearted support and continuous
encouragement. We are grateful to Dr. M.M.Ali, Director CSIBER, Kolhapur for his invaluable guidance.
We take this opportunity to thank Dr.V.M.Hilage, Former Director and Trustee Member, CSIBER,
Kolhapur, Mr. Bharat Patil, Chairman, Mr. Sunil Kulkarni, Vice Chairman, and Deepak Chougule,
Secretary, KIT, Kolhapur, Dr. R.V.Kulkarni, H.O.D., Department of Computer Studies, CSIBER,
Kolhapur for showing a keen interest in the matter of this book and extending all support facilities for the
in-timely completion of this book. Last but not the least we thank all faculty members and non-teaching
staff of department of computer studies, CSIBER, Kolhapur and Production Engineering department,
KIT’s College of Engineering, Kolhapur who have made contribution to this book either directly or
indirectly.

Dr. Poornima G. Naik


Dr. Girish R. Naik

i
Android Lab Manual for Novice

Preface
It gives us an immense pleasure to bring out a book entitled ‘Android Lab Manual for Novice – Vol I’.
In this era of globalization, mobile apps have revolutionized the way the business is conducted.
To cater the needs of customers, IT companies are investing tremendously in app development
which has opened new employability opportunities for computer professionals. Currently
Android is the most popular mobile platform available in the market having more than 85% of
market share. Android operating system is dominating the mobile platform market. Android is an
exciting and evolving technology Google keeps on updating the Android operating system with
new features and enhanced security which is the need of an hour. Since Android is open source it
requires comparatively lesser investment and tremendously reduces development cost. The entire
Android platform is ready for customization which makes simple complex technical
customization The remarkable feature of Android is the minimum time to market which provides
an upper hand and a competitive edge over the rivals. As new android enabled devices are
popping up, the new avenues are opened for Android developers and there is very high demand
for Android developers. With hundreds of millions of users around the world, the possibilities for
gainful employment seem endless. The basic skill sets demand an extensive exposure to Android
IDE and SDK. This book is exactly meant for that which unleashes most of the concepts hidden
behind the set of APIs and brings them infront of the reader. This book is intended for a novice
who is keen in getting first-hand information about Android. The basic skill required for
improving employability opportunities in this area include understanding of layouts and views,
exposure to basic components of Android, android resources, data persistence, to name a few.
The only pre-requisite for understanding the content of this book is the basic knowledge of java
language. The book is thought provoking which motivates the reader to think out of the box and
explore new features available in the application framework.

How this book is organized

Chapter 1 focuses on basic features and architecture of Android and provides insight into
execution of Android application. The main feature of the chapter is setting up development environment
which focuses on setting up ADT bundled eclipse and Android Studio. Android application folder

ii
Android Lab Manual for Novice

structure is explored at depth. Downloading Android platforms and creating AVD for testing Android
applications are also discussed. Chapter concludes with discussion of command-line tools, Android
Debug Bridge (ADB), Activity Manager and Package Manager. Chapter 2 is devoted for basic building
blocks of Android, core Android libraries and different types of layouts understanding of which is crucial
for developing working application in Android. Anatomy of Android application is presented. The
structure of R class and basic elements of AndroidManifest.xml file where the prime system configuration
information resides are also discussed. The main highlight of the chapter is more than one ways of
handling events in Android with are discussed along with suitable examples in each case. Chapter 3
explores different types of resources available in Android. Basic steps involved in creating and using
string resource, string array resource, style resource and menu resource both in eclipse and Android
Studio are discussed. Finally Chapter 4 provides an overview of various pre-defined dialogs available in
Android such as AlertDialog, DatePickerDialog, TimePickerDialog, ProgressDialog and
CharacerPickerDialog which aid in rapid application development and help in rendering the application
user friendly.

The content of this book is derived from different sources which are listed at the end in a
‘references’ section.

Dr. Poornima G. Naik


Dr. Girish R. Naik

iii
Android Lab Manual for Novice

Contents

Chapter Page No.

1. Setting Up Android Development Environment 1


1.1 Introduction of Android 1
1.2 Features of Android 1
1.3 Architecture of Android 2
1.4 Insight into Execution of Android Application 5
1.5 Installing Android 7
1.5.1 Setting up Android for Eclipse IDE 8
1.5.1.1 Creating an Android Virtual Device (AVD) 11
1.5.1.2 Exploring Different Parts of Eclipse IDE 23
1.5.1.3 Testing Android Applications 33
1.5.1.4 Android Application Folder Structure 35
1.5.2 Installation of Android Studio 45
1.5.2.1 System Requirements on Windows Platform 45
1.5.2.2 Setting Up Android Studio 50
1.5.2.3 Developing Applications in Android Studio 55
1.5.2.4 Android Studio Folder Structure 66
1.5.2.5 Creating a Virtual Device in Android Studio 77
1.5.2.6 Executing Android Application in Android Studio 85
1.6 Command Line Tools in Android 90
1.6.1 Android Debug Bridge (ADB) 90
1.6.2 Exploring ADB Commands 91
1.6.3 Introduction to Activity Manager 96
1.6.4 Introduction to Package Manager 98
2. Getting Acquainted With Android Basics 133
2.1 Basic Building Blocks of Android 133
2.2 Elements of the AndroidManifest.xml file 136
2.3 Structure of R Class 141
2.4 Core Android Libraries for Android Developers 144

iv
Android Lab Manual for Novice

2.5 Anatomy of Android Application 145


2.6 Displaying a Message in Android - Toast Class 160
2.7 Event Handling in Android 166
2.8 Writing Messages to Application Log in Android 194
2.9 Layouts in Android 224
2.9.1 Linear Layout 224
2.9.2 Table Layout 233
2.9.3 Absolute Layout 239
2.9.4 Relative Layout 242
2.9.5 Grid Layout 255
2.9.6 Frame Layout 264
2.10 Importing External Projects into Eclipse Workspace 320
3. Exploring Resources in Android 325
3.1 Creating and Using a String Resource in Android 326
3.1.1 Creating String Resource in Eclipse 326
3.1.2 Creating a String Resource in Android Studio 332
3.2 Creating and Using a Style Resource in Android 335
3.3 Creating and Using a String Array Resource in Android 352
3.3.1 Creating String Resource in Eclipse 352
3.3.2 Creating String Resource in Android Studio 358
3.4 Creating and Using a Menu Resource in Android 360
3.4.1 Creating a Menu in Eclipse 360
3.4.1.1 Creating a Submenu 367
3.4.1.2 Creating Mutually Exclusive Menu Items 374
3.4.2 Creating a Menu in Android Studio 385
3.4.2.1 Creating Checked and Disabled Menu Items 391
3.4.2.2 Creating a Sub Menu in Android Studio 393
3.4.2.3 Creating Mutually Exclusive Menu Items 401
3.4.2.4 Creating Multiple Selection Menu Items 404
3.4.2.5 Creating Menu Hierarchy of Mutually Exclusive 408
Items
4. Working with Dialogs in Android 416

v
Android Lab Manual for Novice

4.1 AlertDialog in Android 416


4.2 DatePickerDialog in Android 424
4.3 TimePickerDialog in Android 433
4.4 ProgressDialog in Android 443
4.5 Using CharacterPickerDialog in Android 459
References 467

vi
Android Lab Manual for Novice

CHAPTER 1
Setting Up Android Development Environment
1.1 Introduction of Android
Android is a complete software stack for mobile devices which contains a linux-based
Operating System, middleware and key mobile applications. It can be thought of as a mobile
operating system. But it is not limited to smart phones only. It is currently used in various
devices such as mobiles, tablets, televisions, electronic book readers, set-top boxes, etc.

It is an open source platform which abstracts out the hardware from the software that runs
on it thereby enabling the large number of devices to run the same application. Android does not
make any assumption on device attributes such as screen size, resolution etc. which enhances its
portability to numerous devices.

Android is developed initially by Google and later by OHA (Open Handset Alliance).
Java language is mainly used to write the android code even though other languages can be used.
The goal of android project is to create a successful real-world product that improves the mobile
experience for end users.

What is Open Handset Alliance (OHA)


It's a consortium of 84 companies such as Google, Samsung, AKM, Synaptics, KDDI,
Garmin, Teleca, Ebay, Intel etc. It was established on 5th November, 2007, led by Google. It is
committed to advance open standards, provide services and deploy handsets using the Android
Platform.

1.2 Features of Android


The salient features of Android are enlisted below:
 It is open-source.
 Anyone can customize the Android Platform.
 There are a lot of mobile applications that can be chosen by the consumer.

1
Android Lab Manual for Novice

 It provides many interesting features like weather details, opening screen, live RSS
(Really Simple Syndication) feeds etc.
 It provides support for messaging services(SMS and MMS), web browser, storage
(SQLite), connectivity (GSM, CDMA, Blue Tooth, Wi-Fi etc.), media, handset layout
etc.

1.3 Architecture of Android


Android architecture or Android software stack is categorized into five parts:
 Linux kernel
 Native libraries (middleware),
 Android Runtime
 Application Framework
 Applications

The following figure depicts the layered architecture of Android.

2
Android Lab Manual for Novice

Linux kernel
It is the heart of android architecture that exists at the root of android architecture. Linux kernel
is responsible for device drivers, power management, memory management, device management
and resource access.

Native Libraries
On the top of linux kernel, there are Native libraries such as WebKit, OpenGL, FreeType,
SQLite, Media, C runtime library (libc) etc.
The WebKit library is responsible for browser support, SQLite is for database, FreeType for font
support, Media for playing and recording audio and video formats.

3
Android Lab Manual for Novice

Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is
responsible to run android application. DVM is like JVM but it is optimized for mobile devices.
It consumes less memory and provides fast performance.

Android Framework
On the top of Native libraries and android runtime, there is android framework. Android
framework includes Android API's such as UI (User Interface), telephony, resources, locations,
Content Providers (data) and package managers. It provides a lot of classes and interfaces for
android application development.

Applications
On the top of android framework, there are applications. All applications such as home, contact,
settings, games, browsers are using android framework that uses android runtime and libraries.
Android runtime and native libraries are using linux kernel.

There are two types of Android application developers:


 High-level Android application development using SDK (Software Development Kit)
 Native application development using NDK (Native Development Kit)

Android Versions, Codename and API

The following table depicts the code names, versions and API level for different Android
releases.

4
Android Lab Manual for Novice

1.4 Insight into Execution of Android Application


Dalvik Virtual Machine | DVM
 The modern JVM is high performance and provides excellent memory management. But
it needs to be optimized for low-powered handheld devices as well.

5
Android Lab Manual for Novice

 The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile
devices. It optimizes the virtual machine for memory, battery life and performance.
 Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.
 The Dex compiler converts the class files into the .dex file that run on the Dalvik VM.
Multiple class files are converted into one dex file.

The following figure shows the compiling and packaging process of Android application from
java source files:

6
Android Lab Manual for Novice

The salient features of compilation and packaging process are:


 The javac tool compiles the java source file into the class file.
 The dx tool takes all the class files of your application and generates a single .dex file. It
is a platform-specific tool.
 The Android Assets Packaging Tool (aapt) handles the packaging process.

1.5 Installing Android


There are three ways to install android.
1. By ADT Bundle
2. By Eclipse Setup Manually
3. Using Android Studio

Android studio includes Android SDK and an installer which will install all the required
components with a single click.

Using Eclipse to set up Android Environment


The simplest technique to install required software for android application is using Eclipse. It
requires the following components.
 Eclipse IDE
 Android SDK
 Eclipse Plugin

If you download the Android Studio from android site, you don't need to have eclipse IDE,
android SDK and eclipse Plugin because it is already included in Android Studio.

If you have downloaded the ADT Bundled Eclipse, unjar it, go to eclipse IDE and start the
eclipse by clicking on the eclipse icon. You don't need to do any extra steps here.

7
Android Lab Manual for Novice

1.5.1 Setting up Android for Eclipse IDE


The list of software required to setup android for eclipse IDE manually.
1. Java Development Kit (JDK)
2. Eclipse IDE
3. Android Software Development Kit (SDK)
4. Android Development Tools (ADT) plugin for eclipse

Step 1 : Install the Java Development Kit (JDK).

Step 2 : Download and install Eclipse IDE.

Step 3 : Download ADT plugin for Eclipse.

Install the Java Development Kit (JDK)


For creating android application, JDK must be installed if you are developing the android
application with Java language. Download JDK by visiting Oracle official site.

Download and Install the Eclipse IDE


For developing the android application using eclipse IDE, you need to install the Eclipse. You
can download it from official site of Eclipse. Eclipse classic version is recommended or you can
use the Eclipse IDE for JavaEE Developers.

Download and Install the Android SDK


First of all, download the android SDK. Here android SDK for windows (.exe version) is
installed.

Now double click on the exe file, it will be automatically installed.

8
Android Lab Manual for Novice

Download the ADT Plugin for Eclipse

ADT Plug-in
The ADT plug-in adds Android-specific functionality to Eclipse. Software in the plug-in enables
Eclipse to build Android applications, launch the Android emulator, connect to debugging
services on the emulator, edit Android XML files, edit and compile Android Interface Definition
Language (AIDL) files, create Android application packages (.apk files), and perform other
Android-specific tasks.

ADT (Android Development Tools) is required for developing the android application in the
eclipse IDE. It is the plugin for Eclipse IDE that is designed to provide the integrated
environment.

For downloading the ADT, follow the steps given below:


1. Start the eclipse IDE, and select Help → software Updates from main menu as shown
below:

9
Android Lab Manual for Novice

2. Select “Available Software” tab and click on “Add Site” button and enter the location
given below:
https://dl-ssl.google.com/android/eclipse/

3. Select the checkbox next to ‘Developer Tools’ and click on ‘Next’ button
4. List of tools to be downloaded here is displayed, click on ‘Next’ button
5. Click on ‘Finish’ button.
6. After completing the installation, restart the eclipse IDE.

Configuring the ADT plugin


After installing ADT plugin, configure the android SDK location in eclipse IDE following the
steps enumerated below:
1. Select the menu option Window → Preferences from the main menu.
2. Now select the node ‘Android’ from the left panel
3. Click on the ‘Browse’ button and select the location where Android SDK is installed. For
Example, ‘C:\Program Files\Android\android-sdk ‘.
4. Click the ‘Apply’ button then on OK button.

10
Android Lab Manual for Novice

Android Virtual Device (AVD)

The Android SDK provides an emulator, which emulates a device with an ARM CPU running an
Android operating system (OS), for running Android programs on your PC. An Android Virtual
Device (AVD) is a set of parameters for this emulator that configures it to use a particular system
image—that is, a particular version of the Android operating system—and to set other
parameters that govern screen size, memory size, and other emulated hardware characteristics.

1.5.1.1 Creating an Android Virtual Device (AVD)


It is used to test the android application without the need for a real device, a mobile or a tablet
etc. It can be created in different configurations to emulate different types of real devices.

Android Emulator is used to run, debug and test the android application. If you don't have the
real device, it can be the best way to run, debug and test the application. It uses an open source

11
Android Lab Manual for Novice

processor emulator technology called ‘QEMU’. The ‘emulator’ tool enables you to start the
emulator from the command line.

For running the android application in the Android Emulator, you need to create an AVD. For
creating the AVD follow the steps given below:
1. Select the menu option Window → Android Virtual Device Manager from the main
menu.
2. Click on the ‘New’ button to create the AVD
3. ‘Create New Android Virtual Device (AVD)’ dialog appears, enter the AVD name e.g.
‘siber’. Now choose the Target Android Version, for Example, Android 4.2 and other
configuration details such as skin, memory, internal storage size, SD card size etc.
4. Finally, click on “OK” button to create AVD.

The above steps are depicted in the following figures:

12
Android Lab Manual for Novice

13
Android Lab Manual for Novice

You will need to create an AVD with a system image that is no less recent than the target
specified for the project you created. Click the New button. You will now see the “Create new
Android Virtual Device (AVD)” dialog, shown in the above figure, where you specify the
parameters of your new AVD.

This screen enables you to set the parameters of your new AVD:

Name

This is the name of the AVD. You can use any name for an AVD, but a name that
indicates which system image it uses is helpful.

Target

The Target parameter sets which system image will be used in this AVD. It should be the
same as, or more recent than, the target you selected as the build target for your first
Android project.

SD Card

Some applications require an SD card that extends storage beyond the flash memory built
into an Android device. Unless you plan to put a lot of data in SD card storage (media
files, for example) for applications you are developing, you can create a small virtual SD
card of, say, 100 MB in size, even though most phones are equipped with SD cards
holding several gigabytes.

Skin

The “skin” of an AVD mainly sets the screen size. You won’t need to change the default
for the purpose of verifying that your SDK installation works, but a variety of emulators

14
Android Lab Manual for Novice

with different screen sizes is useful to check that your layouts work across different
devices.

Hardware

The Hardware field of an AVD configuration enables you to set parameters indicating
which optional hardware is present. You won’t need to change the defaults for this
project.

Fill in the Name, Target, and SD Card fields, and create a new AVD by clicking the Create AVD
button. If you have not created an AVD with a system image that matches or is more recent than
the target you specified for an Android project, you won’t be able to run your program.

Now that you have a project that builds an application, and an AVD with a system image
compatible with the application’s build target and API level requirements, you can run your
application and confirm that the SDK produced and is able to run an Android application.

Running a Program on an Android Device

You can also run the program you just created on most Android devices.

You will need to connect your device to your PC with a USB cable, and, if needed, install a
driver, or set permissions to access the device when connected via USB.

If you are running Linux, you will need to create a “rules” file for your Android device.

If you are running Mac OS X, no configuration is required.

You will also need to turn on USB debugging in your Android device. In most cases, you will
start the Settings application, select Applications and then Development, and then see an option
to turn USB debugging on or off.

If an AVD is configured or is running, the Android Device Chooser will appear, displaying both
the Android device you have connected and the AVD.

15
Android Lab Manual for Novice

Select the device, and the Android application will be loaded and run on the device.

Location of AVD Files


Each Android Virtual Device created is located in a folder, ‘C:\Users\Lenovo1\.android\avd’
folder as shown in the following figure:

For every AVD file, there is a corresponding ‘.ini’ file storing the important configuration
information about the AVD. For example for ‘MCA.avd’ file the corresponding configuration
file is ‘MAC.ini’ which contains the following information:

16
Android Lab Manual for Novice

The ‘MCA.avd’ folder contains the disk images files for SD card, configuration information etc.

The content of ‘config.ini’ file is shown below:

17
Android Lab Manual for Novice

Troubleshooting SDK Problems: No Build Targets

If you are unable to make a new project or import an example project from the SDK, you may
have missed installing build targets into your SDK.

Launching AVD from Main Menu


For launching the AVD created above, follow the steps given below:
1. Select the menu option, Window → Android Virtual Device Manager from the main
menu.

2. Select the AVD you want to launch and click on ‘start’ button as shown in the following
figure

3. ‘Launch Options’ dialog appears as shown in the following figure, click on ‘Launch’
button.

18
Android Lab Manual for Novice

The following figure depicts launching emulator. Despite the warning messages displayed,
emulator will launch successfully.

Android emulator starts as shown below:

19
Android Lab Manual for Novice

Handling Errors in Starting Emulator


On many occasions the emulator error, ‘This AVD’s configuration is missing a kernel file!!’ is
displayed as shown in the following figure:

20
Android Lab Manual for Novice

To address this issue perform the steps enumerated below:

1. Right-click on ‘My Computer’ and select ‘Properties’ from shortcut menu.

2. Click on the ‘Advanced’ tab and click on ‘Environment Variables…’ button as shown in
the following figure:

21
Android Lab Manual for Novice

3. Create a new environment variable with the name ‘ANDROID_HOME’ with the value
‘D:\android\adt-bundle-windows-x86-20130522\adt-bundle-windows-x86-20130522\sdk’
pointing to the Android SDK location as shown in the following figure:

22
Android Lab Manual for Novice

4. Create a new environment variable with the name ‘ANDROID_SDK_ROOT’ with the
value ‘D:\android\adt-bundle-windows-x86-20130522\adt-bundle-windows-x86-20130522\sdk’
pointing to the Android SDK location as shown in the following figure:

1.5.1.2 Exploring Different Parts of Eclipse IDE


The following figure depicts different parts of an Eclipse IDE.

The main components of Eclipse IDE are described below:

23
Android Lab Manual for Novice

Package Explorer
It displays a hierarchical view of different files and folders in an Android project

LogCat Windows
It displays different messages written to the log file. The windows contains options for creating
logical group of messages and the messages can be filtered according to the group to view only
the messages in a specific group.

Outline Windows
It displays component tree for the selected layout.

Creating First Android Application in Eclipse IDE


All the examples in this book will be executed using both ADT bundled Eclipse IDE and
Android Studio. On downloading the zip file of ADT bundled Eclipse IDE and extracting an
‘eclipse’ folder is created which contains a folder ‘adt-bundle-windows-x86_64-20130917’ as
shown in the following figure.

24
Android Lab Manual for Novice

Double-click on the folder to open it. The folder contains the following items. The SDK folder
contains the tools for application development and ‘eclipse’ folder contains an executable to
launch Eclipse IDE.

Double-click on ‘eclipse’ folder to open it. It contains the following items:

Create a shortcut to ‘eclipse.exe’ file on the desktop as shown below:

25
Android Lab Manual for Novice

Launching Eclipse IDE


To launch Eclipse IDE, double-click on its short-cut on desktop. The following screen is
displayed.

Browse and select the required workspace. All the Android projects will be created in the
selected workspace. In the current example, all the project folders will reside inside a workspace
folder ‘F:\pgn’.

Select File → New Android Application Project from the main menu as shown below:

26
Android Lab Manual for Novice

To create your Android project, you will have to provide the following information:

Project name

This is the name of the project (not the application) that appears in Eclipse. Type
‘HelloAndroid’, as shown in the following figure.

Workspace

A workspace is a folder containing a set of Eclipse projects. In creating a new project,


you have the choice of creating the project in your current workspace, or specifying a
different location in the file system for your project. Unless you need to put this project in
a specific location, use the defaults (‘Create new project in workspace’ and ‘Use default
location’). In the current example, the name of the workspace folder is ‘F:\pgn’.

27
Android Lab Manual for Novice

Target name

The Android system images you installed in the SDK are shown in the build target list.
You can pick one of these system images, and the corresponding vendor, platform
(Android OS version number), and API level as the target for which your application is
built. The platform and API level are the most important parameters here: they govern the
Android platform library that your application will be compiled with, and the API level
supported—APIs with a higher API level than the one you select will not be available to
your program. For now, pick the most recent Android OS version and API level you have
installed. In the current example, the target SDK is Android 4.2 (API level 17).

Application name

This is the application name the user will see. By default the application name is the same
as project name.

Package name

The package name creates a Java package namespace that uniquely identifies packages in
your application, and must also uniquely identify your whole Android application among
all other installed applications. It consists of a unique domain name—the application
publisher’s domain name—plus a name specific to the application. Not all package
namespaces are unique in Java, but the conventions used for Android applications make
namespace conflicts less likely. In the current example the package name is
‘com.example.helloandroid’, since example.com is a domain name reserved for
examples such as this one.

Minimum SDK version

The field labeled Min SDK Version should contain an integer corresponding to the
minimum SDK version required by your application, and is used to initialize the uses-sdk
attribute in the application’s manifest, which is a file that stores application attributes.

28
Android Lab Manual for Novice

See The Android Manifest Editor. In most cases, this should be the same as the API level
of the build target you selected, which is displayed in the rightmost column of the list of
build targets. . In the current example, the minimum SDK is Android 2.2 (API level 8).

Enter the name of the project as “HelloAndroid” as shown below:

Minimum Required SDK is set to API 8. Lower API levels target more devices but will have
limited features.

Click ‘Next’ two times and then select a blank activity as shown below:

29
Android Lab Manual for Novice

Click on ‘Finish’ button to create a blank Android project.

The folder with the name ‘helloandroid’ is created in the folder ‘F:\pgn’ as shown in the
following figure:

30
Android Lab Manual for Novice

Double-click on the folder to view its contents. The project folder contains the following folders
and files.

All the java source files will be created in a package,


com.example.<project_name>

31
Android Lab Manual for Novice

where, <project_name> is the name of the project specified at the time of creation. In the current
example, the package name is,

com.example.helloandroid

Since in java, a package hierarchy corresponds to a folder hierarchy, the auto-generated class
R.java is located in the folder,

F:\pgn\helloandroid\gen\com\example\helloandroid

as shown in the following figure:

The following folder contains all java source files:

F:\pgn\helloandroid\src\com\example\helloandroid

‘res’ folder contains different subfolders for different types of resources as shown in the
following figure:

32
Android Lab Manual for Novice

‘libs’ folder contains references to external jar files.


‘bin’ folder contains the apk file which is the deployment unit of Android, as shown in the
following figure.

1.5.1.3 Testing Android Applications


There are two ways to test an android application:
i. Using Android Emulator using Android Virtual Device (AVD)
ii. On a real device

33
Android Lab Manual for Novice

Android Virtual Device (AVD)


AVD contains different configurations for emulating different android devices and is used for
testing an android application without using real phone.

Android Emulator
Android Emulator is used to run, debug and test the android application.

Executing Android Application in Eclipse


To execute Android application in Eclipse, right-click on the project in the package explorer and
select Run As → Android Application from the shortcut menu as shown in the following figure:

If more than one emulator is present, the following dialog for selecting the emulator is displayed.

34
Android Lab Manual for Novice

After successful compilation of application ‘helloandroid.apk’ file is created in ‘bin’ folder.


After deploying the ‘helloandroid.apk’ file on a virtual device, the following output is
generated:

The console window displays the progress of deployment as shown in the following figure:

1.5.1.4 Android Application Folder Structure


Android application contains different components such as java source code, string resources,
images, manifest file, apk file etc. The organization of the files in different folders of a project is
shown in the following figure:

35
Android Lab Manual for Novice

The locations of important files of an Android project are shown below:

36
Android Lab Manual for Novice

The following table summarizes the contents of different folders present in a project folder:

Folder Name Description


src This folder contains the Java source files in the project. By default,
MainActivity.java file is created in the package
com.example.projectname where projectname is the name of the
Android Application Project.
gen This folder contains automatically generated files. R.java file
containing resource Ids is automatically generated when the project
is built.
Android <version> Android Jar Files
Android Private Libraries
assets This folder contains the images
bin This folder contains binary Resources – contains apk file
libs This folder contains the JAR files used in the project.
res This folder contains different sub folders containing the different
types of resources used in the android project.

Android Manifest File


This file resides at the root of the application project directory.
 The root node of AndroidManifest.xml file is <application> node which contains the
child nodes representing the different components created in the application.
 The XML attribute ‘android:icon’ will point to the application icon available under
‘res/drawable-hdpi’ folder of a project folder. The application employs the image with
the name ‘ic_launcher.png’ located in the drawable folder under ‘res’ folder.
 The <activity> tag is used to specify an activity with ‘android:name’ XML attribute
pointing to the fully qualified class name of the Activity subclass and the ‘android:label’
attribute specifies a string to use as the label for the activity. Every new activity created
in Android application must first be registered in AndroidManifest file using <activity/>
tag. The <activity> element contains the following child elements.

37
Android Lab Manual for Novice

o The action for the intent filter is named ‘android.intent.action.MAIN’ to indicate


that this activity serves as the entry point for the application.
o The category for the intent-filter is named
‘android.intent.category.LAUNCHER’ to indicate that the application can be
launched from the device's launcher icon.
o The @string refers to the ‘strings.xml’ file. Hence, ‘@string/app_name’ refers to
the key with the name ‘app_name’ defined in the ‘strings.xml’ file, which
contains a value ‘HelloWorld’.

Following table lists the tags which can be used in manifest file to specify different Android
application components –

Tag Name Description


<activity> Specifying element for Android activity
<service> Specifying element for Android Service
<receiver> Specifying element for Broadcast Receiver
<provider> Specifying element for Content Provider

Java source file created by the Eclipse IDE:


This section describes the files generated by eclipse IDE after creating a new project.

The first and important file created by eclipse IDE is ‘MainActivity.java’ containing definition
of MainActivity class. It is located in ‘src’ folder under ‘com.xample’helloandroid’ folder of
project folder in package explorer.

The structure of ‘MainActivity’ class is shown below:

MainActivity.java
package com.example.first_project;
import android.os.Bundle;

38
Android Lab Manual for Novice

import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Activity is a java class that creates a default window on the screen where we can place different
components such as Button, EditText, TextView, Spinner etc. It is like the Frame of Java AWT.
 It provides life cycle methods for activity such as onCreate, onStop, OnResume etc.
 The onCreate method is called when Activity class is first created.
 The setContentView(R.layout.activity_main) gives information about our layout
resource. Here, our layout resources are defined in activity_main.xml file.

The next important file generated by eclipse IDE is layout resource file with the name
‘activity_main.xml’ located in ‘res/layout’ folder under project folder in a package explorer.

39
Android Lab Manual for Novice

Structure of activity_main.xml File

‘activity_main.xml’ is a layout XML file storing information about the container and the
controls present on the container. The root element of ‘activity_main.xml’ file is
<RelativeLayout> and the layout contains a single TextView control whose XML property
‘android:text’ is set to "@string/hello_world” which refers to the string resource with the name
‘hello_world’ present in ‘strings.xml’ file. The structure of ‘activity_main.xml’ file is shown
below:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>

Note: A textview is created by the framework automatically. The message for this string is
defined in the ‘strings.xml’ file. The ‘@string/hello_world’ provides information about the
textview message. The value of the attribute ‘hello_world’ is defined in the ‘strings.xml’ file.

40
Android Lab Manual for Novice

strings.xml
It is an XML file containing definition of string resources. The root node of the XML file is
<resources> which contains one or more child <string> elements. The name of the string
resource is defined in ‘name’ attribute of the <string> element and the content represents the
value of the string resource. The structure of ‘strings.xml’ file is shown below:

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="app_name">first_project</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>

You can change the value of the hello_world attribute from this file.

main.xml
This file contains the menu layout information for the main menu of the application. It contains a
single item with the title defined by a string resource with the name ‘action_settings’ present in
‘strings.xml’ file. The structure of ‘main.xml’ file is shown below:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >


<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
</menu>

AndroidManifest.xml File
It is XML configuration file of the application containing the following information:

41
Android Lab Manual for Novice

 Name of the package.


 Minimum and target SDK versions
 Application’s permissions.
 Information of basic components in the application such as activity, service, broadcast
receiver, content provider etc.

The structure of auto-generated AndroidManifest.xml file is shown below:

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.first_project"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.first_project.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

42
Android Lab Manual for Novice

</application>
</manifest>

Starting AVD From Command Line


The location of AVD files created in Eclipse is ‘C:\Users\Lenovo1\.android’, where ‘lenovo1’ is
the name of the logged in user as shown in the following figure:

The executable for launching emulator is ‘emulator.exe’ which is located in the folder,
F:\eclipse\adt-bundle-windows-x86_64-20130917\sdk\tools
as shown below:

For launching AVD from command-line, start command-line and move to the folder

43
Android Lab Manual for Novice

F:\eclipse\adt-bundle-windows-x86_64-20130917\sdk\tools

Next, enter the following command in the command-line.


emulator -avd <AVD_NAME>
where, AVD_NAME is the name of the AVD to be launched as shown below:

The emulator starts as shown in the following figure:

44
Android Lab Manual for Novice

1.5.2 Installation of Android Studio


1.5.2.1 System Requirements on Windows Platform
The minimum system requirements for installing Android Studio on a Windows platform are
listed below:

 Microsoft Windows 7/8/10 (32-bit or 64-bit)


 3 GB RAM minimum, 8 GB RAM recommended (plus 1 GB for the Android Emulator)
 2 GB of available disk space minimum, 4 GB recommended (500 MB for IDE plus 1.5
GB for Android SDK and emulator system image)
 1280 x 800 minimum screen resolution

Download latest version of Android Studio by visiting its official website,


https://developer.android.com/studio/index.html

Accept the license agreement and click on button ‘Download Android Studio for Windows’
shown in the following figure:
45
Android Lab Manual for Novice

The name of the Android Studio executable file is:


android-studio-ide-183.5692245-windows.exe

After downloading the ‘android-studio-ide-183.5692245-windows.exe’ file, for installing


Android Studio follow the steps enumerated below:

Pre-requisite for Android Studio


For successful installation of Android Studio, JDK is required to be installed on the target
system and the environment variable JAVA_HOME should be setup to point to the JDK
installation folder as shown in the following figure:

46
Android Lab Manual for Novice

Step 1: Right click on downloaded ‘.exe’ file and select the option ‘Run as Administrator’ from
the shortcut menu. The setup wizard launches as shown in the following figure:

47
Android Lab Manual for Novice

Click on the ‘Next’ button.

Step 2: Place a check mark next to ‘Android Virtual Device’ and click on ‘Next’ button

Step 3: The default installation path is ‘C:\Program Files\Android\Android Studio’. For


installing Android Studio at some other location, click on the ‘Browse…’ button and select the
installation folder, else accept the default location and click on the ‘Next’ button.

48
Android Lab Manual for Novice

Step 4: The next step prompts for specifying the start menu folder for the Android Studio
shortcut. Accept the default and click on ‘Install’ button.

Step 5: Installation commences as shown in the following figure:

49
Android Lab Manual for Novice

Step 6: After the installation is complete, place a check mark next to ‘Start Android Studio’
option and click on ‘Finish’ button.

1.5.2.2 Setting Up Android Studio

On launching Android Studio, Android Studio Setup Wizard will start which displays a welcome
screen as shown in the following figure:

50
Android Lab Manual for Novice

Click on ‘Next’ button to proceed to next screen.

Step 7: This step prompts for selection of installation type. Select ‘Standard’ and click on ‘Next’
button. The following dialog is displayed:

Step 8: The next screen prompts for the selection of UI theme which is by default IntelliJ.
Accept the default and click on ‘Next’ button to proceed.

51
Android Lab Manual for Novice

Step 9: In the next step review the settings, once verified, click on ‘Finish’ button to download
the selected components.

Step 10: The necessary components for launching Android Studio and setting up the
environment will be downloaded as shown in the following figure:

52
Android Lab Manual for Novice

After download is complete click on ‘Finish’ button. This completes the procedure for installing
and setting up Android Studio.

Android Studio Projects


Android Studio project contains everything that defines a workspace for and Android application
which contains application source code, application configuration information, assets among
other important information.

Android View
By default the project files are displayed in an Android view which is organized according to
different file types for ease of navigation.

Gradle

Gradle is the Android Studio build tool which takes different source files, compiles and packages
them into an ‘apk’ file which is the deployment unit of Android. It is used for automating the
process of program compilation.

Comparison Between Ant, Maven and Gradle

All the three are java build automation tools. Ant is strictly a build tool with no dependency
management. The major benefit offered by Ant is its flexibility. Ant doesn’t impose any coding
conventions or project structures. But the downside is no dependency management.

On the other hand Maven is build automation tool with dependency management tool. Maven
relies on conventions and provides predefined commands.

Gradle is a dependency management and a build automation tool which was built upon the
concepts of Ant and Maven which combines best of both worlds – Ant’s flexibility and Maven’s
features. Unlike Ant and Maven, Gradle does not use XML files which led to the smaller

53
Android Lab Manual for Novice

configuration files. Gradle’s configuration file is by convention called build.gradle. The


following figure shows the project structure in Android Studio.

54
Android Lab Manual for Novice

1.5.2.3 Developing Applications in Android Studio


Launch Android Studio by double-clicking on its short-cut on desktop shown below which is
created after successful installation of Android Studio.

The following screen is displayed.

Click on the first option ‘Start a new Android Studio Project’.

Alternatively, select File → New → New Project from the main menu as shown in the following
figure:

55
Android Lab Manual for Novice

The following dialog is displayed:

56
Android Lab Manual for Novice

Enter the name of the project in the ‘Application name’ text box and click on ‘Next’ button.
In the next screen accept the default ‘Phone and Tablet’ for Android Target Devices and click
on ‘Next’ button.

Select ‘Empty Activity’ and click on ‘Next’ button.

57
Android Lab Manual for Novice

Click on ‘Next’ button.

Accept the default activity name as ‘MainActivity’ and layout name as ‘activity_name’ and click
on ‘Finish’ button.

Android Studio will start creating the project as demonstrated in the following figure:

After the gradle build process is complete the following screen is displayed:

58
Android Lab Manual for Novice

The structure of ‘MainActivity’ class created by Android Studio is shown below:

59
Android Lab Manual for Novice

As seen from the above generated code, ‘MainActivity’ class is derived from
‘AppCompatActivity’ class.

Difference Between Activity and AppCompatActivity


AppCompatActivity is the direct child class of FragmentActivity of support v4 and the direct
parent class of ActionBarActivity. The definition of AppCompatActivity class is shown below:

As seen from the above figure, AppCompatActivity class is directly derived from
FragmentActvity class.

Activity is the fundamental block of creating Android Application. Activity is the base Class of
all other Activities as shown in the following figure:

60
Android Lab Manual for Novice

From the above figure it is clear that, AppCompatActivity inherits FragmentActivity and
FragmentActivity inherent Activity.
Hence,
 If you want the backported Material Design look, use AppCompatActivity
 If not, but you want nested fragments, use FragmentActivity
 If not, use Activity

The ‘app’ folder is the root folder which consists of the following sub-folders:

 manifests – An important file in this folder is Android application configuration file,


‘AndroidManifest.xml’ file.

 src folder contains all the source code and resource files for the module in various sub-
folders shown below:

o java – This folder contains the packages containing java classes with source code
of the application classes.

o androidTest – Contains code for instrumentation tests

 res – This folder contains the following sub-folders

 drawable – This folder contains image resources


 layout – This folder contains layout files in XML format.
 mipmap – This folder contains application icon files
 values – This folder in turn contains the following sub-folders
 colors.xml
 dimens.xml
 strings.xml
 styles.xml

Assets Folder
This folder contains files which are to be compiled into an ‘apk’ file as-is.

61
Android Lab Manual for Novice

The following figure shows the default layout of the application. The layout can be manipulated
from two different views:
 Design View - XML view through coding

 Text View - GUI view using drag-drop operations

62
Android Lab Manual for Novice

Gradle Scripts

In the ‘Android’ view, the ‘Gradle Scripts’ section contains two important Gradle scripts:

 build.gradle (module)
 build.gradle (project)

as shown in the following figure:

The file build.gradle (module) defines module specific build configurations while build.gradle
(project) defines build configurations global to all the modules.

The snapshot of build.gradle (module) is shown below:

63
Android Lab Manual for Novice

The following figure shows the snapshot of build.gradle (project).

The important entries in this file are

 Minimum SDK Version


 Target SDK Version

Viewing Project Structure Settings


For viewing various settings for Android Studio project, select File → Project Structure from
main menu as shown in the following figure:

64
Android Lab Manual for Novice

The following dialog is displayed which lists locations of SDK and JDK.

The SDK location is:


C:\Users\Lenovo1\AppData\Local\Android\Sdk

The JDK location is


C:\Program Files\Android\Android Studio\jre

The content of the folder ‘C:\Program Files\Android\Android Studio’ is shown below:

65
Android Lab Manual for Novice

1.5.2.4 Android Studio Folder Structure


Exploring Android SDK Folder Structure
Android SDK Folder Structure
The following figure depicts the structure of Android SDK folder

The description of different sub-folders of Android SDK folder is given in the following table:

66
Android Lab Manual for Novice

Folder Name Description


Platforms This folder contains the build targets that are
installed on the system for building
applications compatible with different Android
API levels. Build targets can be installed using
SDK and AVD Manager. This tool enables you
to install packages in the SDK that will support
multiple versions of the Android OS and
multiple API levels.
tools These are the development and debugging
tools for the Android SDK
platform-tools The Platform tools contain additional tools for
connecting to devices and emulators to deploy
builds and debug applications
These tools are updated for every new version
of the Android platform to support new
features, and each update is backward
compatible with older platform versions.
extras This folder contains support libraries for
additional APIs. This folder is created if you
download some extras from Android SDK
Manager
Build-tools These tools are required for building Android
apps.
The Build Tools are required for actually
building/compiling your source code into an
application that can be run on the Android
platform.
System-images A system image is a file — or set of files —
that contains everything on a PC's hard drive,
or just from one single partition. A system

67
Android Lab Manual for Novice

imaging program looks at the hard drive,


copying everything bit by bit. You then have a
complete system image you can copy back
onto a drive to restore the system state.

The following figure shows the content of ‘Extras’ folder.

The following table describes different SDK tools:

Tool Name Location Description


adb /sdk/platform-tools Android Debug Bridge (adb) is a
versatile tool that lets you
manage the state of an emulator
instance or Android-powered
device. You can also use it to
install an APK on a device.

68
Android Lab Manual for Novice

logcat This is a tool invoked via adb to


view app and system logs.
emulator /sdk/tools A device-emulation tool that you
can use to debug and test your
applications in an actual
Android run-time environment.

The content of the folder ‘C:\Users\Lenovo1\AppData\Local\Android\sdk’ is shown below:

This section describes the content of different folders constituting Android SDK.

 add-ons Folder
This folder hosts additional libraries such as Google Maps as shown below:

69
Android Lab Manual for Novice

 docs Folder
This folder contains Android SDK API reference documentation.

The important file in this folder is ‘index.html’ shown in the following figure:

70
Android Lab Manual for Novice

 Platforms Folder
The heart of Android SDK folder is ‘platforms’ which contains SDK real file for
each platform which contains the following sub-folders:
o Skins folder contains the Android emulator skin,
o Templates folder is the default template project to create,
o Android.jar is the main framework file in this version

 Platform Tools
Platform-tools folder holds some general tools, such as ADB, and AAPT, Aidl,
DX file,fastboot etc.

 Tools Folder
7 important tools in the ‘tools’ sub-folder of ‘sdk’ folder are described below:

71
Android Lab Manual for Novice

 ddms (Davlik Debug Monitor Server) tool is used to start the Android debugger,
Such as logcat, screenshots and file manager
 draw9patch is the Android platform scalable PNG image tool
 SQLite3 tool is used to operate SQLite database
 monkeyrunner is a good application of pressure test,
 mksdcard is a simulator tool for SD image creation
 emulator is the main program of Android simulator,
 traceview is an important Android platform debugging tool.

Android Platforms
The following figure depicts the android platforms installed on the current system:

Android System Images


The following figure depicts the system images installed on the current system. As can be seen
from the figure, even though three android platforms are installed, there are system images only
for the platforms ‘android-19’ and ‘android-24’. The system image for ‘android-25’ is missing.
When the AVD is created to use the platform ‘android-25’, the message ‘missing system image’
is displayed.

72
Android Lab Manual for Novice

Difference Between tools, build-tools and platform-tools Folder

Build-Tools Folder
This folder contains the tools required for building Android apps. All the build tools are located
in the ‘build-tools’ sub-folder of ‘sdk’ folder. To point out important tools in this folder are:
dx.bat, aapt.exe, aidl.exe, dexdump.exe etc. It includes the complete set of development and
debugging tools for the Android SDK like emulator, sdcard, sqlite and apk builder etc.

Tools Folder
This folder includes the complete set of development and debugging tools for Android.

Platform Tools Folder


Platform-tools folder contains the tools to interact with the android device such as fastboot and
adb. Platform-tools are used to support the features for the current android platform including
adb which is acting like a bridge to communicate with emulator or device.

73
Android Lab Manual for Novice

Note: If you are deploying for a API 19 device, you should also have the Android SDK platform
19.
The quick glance at the few important SDK tools, build tools and platform tools is shown below:

SDK Tools:

1. Android SDK Manager (sdkmanager)


2. AVD Manager (avdmanager)
3. Dalvik Debug Monitor Server (ddms)

Platform Tools:

1. adb
2. fastboot
3. dmtracedump
4. etc1tool
5. sqlite3

Build Tools:

1. adb
2. aidl, aapt, dexdump, and dx
3. bmgr
4. logcat

Displaying Properties of a Widget in Android Studio

When the widget is selected in the layout the table listing the frequently used properties of a
widget is displayed as shown in the following figure:

74
Android Lab Manual for Novice

To view all the properties of a control, click on the link, ‘View all properties’. The following
table listing all the properties of a control is displayed:

75
Android Lab Manual for Novice

If you try to change the ID of a widget in design view, the following dialog box is displayed for
updating all references to the widget in R file and other source files referencing the widget.

76
Android Lab Manual for Novice

Location of Android Studio Projects


All the projects created in Android Studio are stored in a folder
C:\Users\<user_name>\AndroidStudioProjects
where, <user_name> is the name of the logged in user.

In the current system, all Android Studio projects are stored in the location
C:\Users\Lenovo1\AndroidStudioProjects
of hard drive as shown in the following figure:

1.5.2.5 Creating a Virtual Device in Android Studio


Installing an Android System Image
Before creating an Android emulator it is required to install Android system image for the
emulator to use.

77
Android Lab Manual for Novice

When Android SDK is installed a valid Android system image should already be installed in
Android SDK Manager. If due to some reason the system image is not installed, then it can be
installed manually by launching Android SDK Manager.

For starting Android SDK Manager, navigate to the folder,

C:\Users\Lenovo1\AppData\Local\Android\sdk\tools

and locate the file ‘android.bat’ and double-click on it to launch Android SDK Manager.

Android SDK Manager is launched as shown in the following figure. As can be seen from the
following figure, for the android-25 platform, the SDK is installed but the system images are
missing.

78
Android Lab Manual for Novice

For installing system images for android-25 platform, select the required images by placing a
check mark next to the image as shown in the following figure (Atom_64 or ARM) abd scroll to
the bottom.

79
Android Lab Manual for Novice

Depending on the no. of packages selected the caption of the button will change. In the current
example 17 packages are selected. Hence the caption of the button will change to ‘Install 17
Packages’.
Click on ‘Install 17 Packages’

80
Android Lab Manual for Novice

The dialog displays the packages selected for installation.

Accept License Agreement and click on ’Install’ button


81
Android Lab Manual for Novice

The installation commences as shown in the above figure and the missing SDK and system
images are installed.

For creating a virtual device in Android Studio there are two options:

82
Android Lab Manual for Novice

1. Selecting the option Tools → Android → Virtual Device Manager from main menu.
OR
2. Clicking on ‘Create New Virtual Device’ button in ‘Select Deployment Target’ window
which appearing on execution of Android application as shown in the following figure:

In the above window, click on ‘Create New Virtual Device’ button. The following window
appears for selecting the hardware device, since Android application can be executed on variety
of hardware devices including tablet, TV, wearable device apart from phone. In the dialog that
appears select ‘Phone’.

83
Android Lab Manual for Novice

In the next screen that appears select the system image and click on ‘Next’ button.

84
Android Lab Manual for Novice

Enter AVD name as ‘MCA’ and click on the ‘Finish’ button.

1.5.2.6 Executing Android Application in Android Studio


• To run the android application, click the run icon on the toolbar or simply press Shift + F10.
• The android emulator might take 2 or 3 minutes to boot. After booting the emulator, the
android studio installs the application and launches the activity.

85
Android Lab Manual for Novice

Android application can be executed in one of several ways shown below:


By pressing the key combination Alt +Shift +F10
OR
Selecting right-pointing green arrow tool from tool box.
OR
Selecting Run → Run ‘app’ option from main menu as shown in the following figure:

Adopting any of these methods displays the following dialog for selecting the deployment target
which can be a real device or one of the virtual devices created earlier. The dialog lists all the
available virtual devices as shown in the following figure:

86
Android Lab Manual for Novice

From the list of virtual devices displayed above, select an AVD with the name ‘MCA’ created
earlier. The emulator starts up as shown in the following figure:

and the application gets deployed on the virtual device as shown in the following figure:

87
Android Lab Manual for Novice

Restoring Layout in Android Studio


If accidently, the windows get cluttered in Android Studio, then the default layout can be
restored by selecting Window → Restore Default Layout from the main menu as shown in the
following figure:

As shown in the above figure, the shortcut key for achieving the same task is Shift + F12.

Opening Existing Projects in Android Studio


Existing projects can be opened in Android Studio in one of several ways:
1. Close the currently open project by selecting File → Close Project from the main menu
as shown in the following figure:

2. The recently created projects are displayed as shown in the following figure. If the
project is listed in the recent projects list, select it. Otherwise, select the option ‘Open an
existing Android Studio project’ shown in following figure:

88
Android Lab Manual for Novice

3. Navigate to ‘C:\Users\Lenovo1\AndroidStudioProjects’ folder, select the required


project and click on ‘OK’ button to open it in the editor.

89
Android Lab Manual for Novice

Exiting Android Studio


For exiting from Android Studio, either select File → Exit from the main menu or click on the
close button of a main window. The ‘Confirm Exit’ dialog is displayed as shown below:

Click on ‘Exit’ button to exit from Android Studio.

1.6 Command Line Tools in Android


The Android SDK consists of multitude of packages that are required for app development.

1.6.1 Android Debug Bridge (ADB)

Android Debug Bridge (adb) is a versatile command-line tool that lets you communicate with a
device (an emulator or a connected Android device). The adb command facilitates a variety of
device actions, such as

 installing apps
 debugging apps, and
 it provides access to a Unix shell that you can use to run a variety of commands on a
device.

Working of ADB

The ADB client works as described bellows:

90
Android Lab Manual for Novice

 When the ADB client starts it first checks whether the server process is running. If not it
will start a new server process.
 The server listens to all commands sent from ADB client across port 5037.
 The emulators are searched by scanning odd numbered ports in the range 5555 to 5585
which consists of ports used by first 16 emulators.
Note: Each emulator uses two contiguous ports, even port for console connections and
odd port for ADB connections. For example, the following emulator uses the port 5554
for console connection and 5555 for ADB connection.

 Once the server establishes a connection to the device ‘adb’ command can be used to
access the devices.

1.6.2 Exploring ADB Commands

Listing ADB Commands

For listing all ADB command, start command prompt, change to the folder

F:\eclipse\adt-bundle-windows-x86_64-20130917\sdk\platform-tools

91
Android Lab Manual for Novice

and enter the command

adb

in the command prompt.

All ‘ADB’ commands are listed as shown in the following figure:

‘adb devices’ Command


This command displays list of devices attached. The following figure shows the execution of the
command.

If the device is not up and running, has just started then the following output is generated:

92
Android Lab Manual for Novice

If the device is up and running then the output generated is shown in the following figure:

Displaying adb Shell


The command for displaying adb shell is

adb shell

The following figure shows the execution of the command:

93
Android Lab Manual for Novice

Without starting emulator if this command is issued then the error message ‘device not found’ is
generated as shown in the following figure:

Logging into ADB Shell as a ‘root’ User

Resetting the ADB Host


The following command is used for resetting the ADB host:

adb kill-server

94
Android Lab Manual for Novice

As shown in the above figure, if the command ‘adb devices’ is issued when no daemon process
is running, the daemon process is started automatically on port 5037.

Alternatively, the daemon process can be started by issuing the following command:
adb start-server
and then any ADB command can be executed as shown in the following figure:

Sending Command to a specific Device


When multiple devices are connected, the commands can be sent to a specific device using –s
option (where –s option stands for serial no. of a device). As shown in the following figure, there
are two connected devices:

For sending command to a device with serial no, ‘emulator-5554’ use the following command:

95
Android Lab Manual for Novice

adb -s emulator-5554 install hello.apk


which installs ‘hello.apk’ on a device with serial no. ‘emulator-5554’

1.6.3 Introduction to Activity Manager

Call activity manager (am)


Within an adb shell, you can issue commands with the activity manager (am) tool to perform
various system actions, such as start an activity, force-stop a process, broadcast an intent, modify
the device screen properties, and more. While in a shell, the syntax is:

am command

You can also issue an activity manager command directly from adb without entering a remote
shell using the following syntax:

adb shell am start –a android.intent.action.VIEW

For instance, Android Studio uses the following command for executing the project using
Activity Manager as shown in the following figure:

adb shell am start -n


"com.example.lenovo1.layoutproject/com.example.lenovo1.layoutproject.MainActivity" -a
android.intent.action.MAIN -c android.intent.category.LAUNCHER

96
Android Lab Manual for Novice

Changing Display Size and Resolution

The syntax for changing the display size of a device is shown below:

display-size [reset |widthxheight]

This command is helpful for testing your app across different screen sizes by mimicking a small
screen resolution using a device with a large screen, and vice versa.

Example:
am display-size 1280x800

Changing Display Density

The syntax for changing the display density of a device is shown below:

display-density dpi

This command is helpful for testing your app across different screen densities on high-density
screen environment using a low density screen, and vice versa.

Example:
am display-density 480

The execution of the above commands is shown in the following figure:

97
Android Lab Manual for Novice

1.6.4 Introduction to Package Manager

Call package manager (pm)

Within an adb shell, you can issue commands with the package manager (pm) tool to perform
actions and queries on application packages installed on the device. While in a shell, the syntax
is:

pm <command>

You can also issue a package manager command directly from adb without entering a remote
shell. For example:

adb shell pm uninstall com.example.myapp

‘adb shell pm list packages’ Command


This command lists both the pre-defined android packages and custom packages as shown in the
following figure:

98
Android Lab Manual for Novice

‘adb shell pm list permission-groups’ Command


This command lists all known permission groups, optionally only those in a group.

‘adb shell pm list permissions’ Command


This command lists different Android permissions.

99
Android Lab Manual for Novice

‘adb shell pm list features’ Command


This command lists hardware features.

‘adb shell pm list libraries’ Command


Prints all the libraries supported by the current device

100
Android Lab Manual for Novice

‘adb shell pm list users’ Command


The above command prints all users on the system.

Creating Multiple Users in Android

101
Android Lab Manual for Novice

The following command is used for specifying maximum no. of users:


adb shell setprop fw.max_users 4

The following command is used for creating a user with the name ‘pgn’.
adb shell pm create-user pgn
This command is used for creating a new ADB user. Create a new user with the given
user_name, printing the new user identifier of the user

‘adb shell pm get-max-users’ Command


Prints the maximum number of users supported by the device.

102
Android Lab Manual for Novice

The following figure shows creating a user.

adb shell pm list instrumentation


The above command lists all test packages.

‘adb devices –l’ Command


It displays the list of ADB devices connected to ADB server. The status information printed for
each device consists of the following

103
Android Lab Manual for Novice

 The first column displays the string created by ADB to uniquely identify the device and
its port no. The string has the following format ‘emulator - <port_no>’ where port no is
the port used by the emulator for console connection.
 The second column displays the state of the device which can be one of the following:

Device State Description


offline The device is connected to ADB but not booted
device The device is connected to ADB server
no device No device is connected to ADB

1. Starting Emulator from command line.

emulator –avd siber

104
Android Lab Manual for Novice

The emulator launches as shown in the following figure:

Introduction to SDK Manager


SDK Manager

Android SDK Manager Packages


The Android SDK Manager allows you to select which packages you want to install as shown in
the following figure where six packages are selected for installation.

105
Android Lab Manual for Novice

Android SDK Tools


The first option you’ll see is the Android SDK Tools. These are the development and debugging
tools for the Android SDK and you’ll need these installed in order to compile Android
Applications. Install this and keep it up to date.

Android SDK Platform-tools


The Platform tools contain additional tools for connecting to devices and emulators to deploy
builds and debug applications. You should always have the latest version of the platform tools to
ensure compatibility with the latest version of the Android APIs; so keep this up to date as well.

106
Android Lab Manual for Novice

Android SDK Build-tools


The Build Tools are required for actually building/compiling your source code into an
application that can be run on the Android platform. You should always install the latest version
which will be used by default during compilation. If your project depends on an older version,
the SDK Manager allows you to install and maintain separate versions.

Android APIs
After the Tools section you’ll see sections for each Android API. Typically when a new version
of the Android operating system is released, Google also updates the APIs which allow you to
develop with the latest features and fixes. You’ll see the Android version listed (i.e. 4.4.2) along
with the API level (API 19) as shown in the following figure:

107
Android Lab Manual for Novice

Documentation for Android SDK


There is documentation for each API level and this is written for Java Android developers.
Optionally, it can be installed but it’s not often recommended.

SDK Platform
The SDK Platform for a given API level allows you to compile against that version of Android.
Newer platforms require newer versions of the SDK Platform-tools and SDK Tools which is why
we need to keep those up to date.

Samples for SDK

These are Java samples included with each API level which can be installed on need basis.

System Images
These are system images that can be used with Android virtual devices. On later API levels, both
ARM and x86 images are included. The x86 images will run significantly faster and should be
preferred over the ARM equivalents. The images prefixed with ‘Google APIs’ include the
Google Play Services runtime and are useful for testing Google Play Services features such as
mapping. These versions are recommended over the ‘plain’ versions.

Note – the System Images take up a significant amount of disk space so you should only install
them if you’re using them.

Google APIs
Most API levels include a package called Google APIs. This includes additional documentation,
samples and libraries for the Google APIs for that version of Android for Java developers. These
libraries are only needed if you’re coding using the Google APIs.

Sources for Android SDK


For some API levels Google has released the source code. Unless you’re specifically interested
in viewing the source code for the Android SDK, do not installing it, and it’s not needed for
application development.

108
Android Lab Manual for Novice

Which API Levels to Install?


In an ideal world you would just install the latest version, since you can still target older versions
of Android with the latest SDK. However, APIs do change between versions and with that, you
may find example code or example projects that are designed for, and targeting older versions.
The good news is, each SDK Platform only uses about 100 megabytes of space. So for
simplicity, you can safely install every SDK Platform (which will consumes ~2GB of space).

Extras
The final section is Extras. The packages in this section include extra functionality and tools you
can optionally use during development as shown in the following figure:

109
Android Lab Manual for Novice

Android Support Library


The Android Support Library is a package that provides backwards compatibility for new API
features on older devices. Additionally, Google releases some features and controls that are
ONLY available in the support libraries. It’s considered “best practice” to use the Support
Libraries for some features during development.

Google Play Services


The Google Play Services provide APIs to develop using extra Android features created by
Google, this includes technologies such as Google Maps and Google+.

Note – devices must have the Google Play Services Runtime installed to use these additional
APIs. Almost all new Android devices include the runtime - notable exclusions include the
Kindle Fire devices. Generally, Android emulators don’t include the Google Play Services
runtime by default but it can be installed separately.

Google USB Driver


The Google USB Driver enables USB debugging for most Android devices from Windows.

Note - for some devices, you may need to install device specific drivers provided by the
manufacturer. USB debugging is somewhat inconsistent on Windows 8.x, it can be unreliable to
connect and some devices tend to work more reliably than others (ie Nexus). The driver isn’t
used on OSX.

Starting SDK Manager


Double click on android.bat file located in the folder

D:\android\adt-bundle-windows-x86-20130522\adt-bundle-windows-x86-20130522\sdk\tools

110
Android Lab Manual for Novice

The SDK Manager can also be launched from eclipse menu. Launch eclipse and select Window
→ Android SDK Manager as shown in the following figure:

Android SDK Manager window opens up as shown in the above figure:

111
Android Lab Manual for Novice

Viewing Contents of SD Card


Select window -> Open Perspective and DDMS from the Main Menu.
Select File Explorer. The following window is displayed.

‘android list targets’ Command


The above command lists the available target devices as shown in the following figure:

112
Android Lab Manual for Novice

‘android create avd –n mba –t android-17’ Command


This command is used for creating AVD from command-line.

‘android list avd’ Command


The above command lists the available target devices as shown in the following figure:

113
Android Lab Manual for Novice

‘adb –e install –r hello.apk’ Command


The above command is used for installing the APK file on the emulator as shown in the
following figure:

Launching Application from ADB Shell


Activity Manager tool can be used for launching applications from ADB shell. The command for
launching android application from command-line is shown below:

am start –n com.example.hello/.MainActivity

114
Android Lab Manual for Novice

The prime steps involved in launching android applications from command-line are listed below:

Step 1 : sdk/tools/>android list avd

Step 2: sdk/tools>emulator –avd siber

Step 3 : sdk/platform-tools>adb devices

Step 4 : adb shell

Step 5 : # am start -n com.example.hello/.MainActivity

The following figure shows the execution of above commands:

The output generated after launching the ‘hello’ project from command-line is shown in the
following figure:

115
Android Lab Manual for Novice

Creating SD Card
The command for creating SD card is

mksdcard 128M my128MbCard


It accepts two arguments, the size and name of the SD card. The execution of the command is
shown in the following figure:

116
Android Lab Manual for Novice

Making Android File System RW


The ‘sdcard’ folder is read-only. If you try to push the local file to ‘sdcard’ folder, an error
message is generated. The issue can be resolved by granting the read-write permission to the
‘sdcard’ folder as described below:

1. Start command prompt and change to the folder,


F:\eclipse\adt-bundle-windows-x86_64-20130917\sdk\platform-tools

2. Enter the following command from the command prompt:


adb shell
ADB shell prompt ‘#’ is displayed.

3. Next, enter the following commands from adb shell


mount -o rw,remount rootfs /
chmod 777 /mnt/sdcard

Working with external storage in the Android emulator could be a little tricky and the
documentation is not easy to find. I’ll try to give a brief walk through of the steps needed to
create a SD card image, mount the image in Linux, put content on it and use it in the emulator.

Creating a SD card image

In both the 1.1 and 1.5 version of the SDK there is a tool called mksdcard located in the ‘<SDK
Install Dir>/tools’ folder. Simply run the following command:

./mksdcard 128M my128MbCard

to create a 128Mb SD card with the name my128MbCard.

117
Android Lab Manual for Novice

Mounting a SD card image in Linux

To be able to put content on to the card you can mount the card in Linux. It will then simply
appear as a folder in the file system.

First make a directory in the /media folder:

sudo mkdir /media/mycard

Then mount the card as a loopback device using the following command:

sudo mount -o loop my128MbCard /media/mycard

Adding content to the card

With content we usually mean media content like images and videos. Images and videos are
located in a folder called ‘/dcim/Camera’. You could of course add any content to the card.
When you are done copying your files be sure to mount the card otherwise it will not be usable
from the emulator.

sudo umount /media/mycard/

Using the card in the emulator

Google added something called Android Virtual Device (AVD) to the SDK 1.5. To create a new
AVD using our newly created SDcard image run the following:

./android create avd --name myAVD --target 2 --sdcard my128MbCard

Target 2 means that we want to use the 1.5 API features in the device. Now we simply fire up the
emulator and start using our content:

./emulator -avd myAVD

118
Android Lab Manual for Novice

Viewing Contents of SD Card in adb shell


Launch ADB shell and enter the command ‘ls’ in ADB shell. The following output is generated:

Start ADB shell by issuing the command:


adb shell
Switch to ‘/mnt/sdcard’ folder and ‘ls’ the folder using the following commands:
# cd /mnt/sdcard
# ls

Opening ADB Shell when multiple Devices are Connected


Start ADB shell by issuing the command:
adb shell

119
Android Lab Manual for Novice

Enter the following command in ADB shell to list all connected devices:
adb devices
To connect to the emulator ‘emulator-5554’ enter the following command in ADB shell:

adb -s emulator-5554 shell

Open another command window and launch ADB shell. For connecting to the emulator
‘emulator-5556’ enter the following command in ADB shell:

adb -s emulator-5556 shell

120
Android Lab Manual for Novice

If the command is issued without specifying the target device ‘adb’ generates an error as shown
in the following figure:

Setting Up Port Forwarding


The forward command can be used to set up port forwarding which forwards the request on a
specific port to a different port. For example, for forwarding all requests to port 6000 to port
7000, use the following command:

adb forward tcp:6000 tcp:7000

Copying Files to a Device – pull Command

Copying Files from a Device – push Command


Use the pull and push commands to copy files to and from an device. Unlike the install
command, which only copies an APK file to a specific location, the pull and push commands let
you copy arbitrary directories and files to any location in a device.

To copy a file or directory and its sub-directories from the device, do the following:

adb pull remote local

121
Android Lab Manual for Novice

To copy a file or directory and its sub-directories to the device, do the following:

adb push local remote

Replace local and remote with the paths to the target files/directory on your development
machine (local) and on the device (remote). For example:

adb push test.txt /sdcard/test.txt

Copying File from the Local File System


The command used for pushing the local file on ‘sdcard’ is shown below:

adb push C:\testdata\t.txt /sdcard/download/t.txt

122
Android Lab Manual for Novice

Components of the SDK

The Android SDK is made of mostly off-the-shelf components, plus some purpose-built
components. In many cases, configurations, plug-ins, and extensions adapt these components to
Android. The Android SDK is a study in the efficient development of a modern and complete
SDK. Google took this approach to bring Android to market quickly. You will see this for
yourself as you explore the components of the Android SDK. Eclipse, the Java language,
QEMU, and other preexisting platforms, tools, and technologies comprise some of the most
important parts of the Android SDK.

In creating the simple program that confirms that your SDK installation is correct, you have
already used many of the components of the SDK. Here we will identify and describe the
components of the SDK involved in creating your program, and other parts you have yet to use.

The Android Debug Bridge (adb)

The Android Debug Bridge (adb) is a program that enables you to control both emulators and
devices, and to run a shell to execute commands in the environment of an emulator or device.
Adb is especially handy for installing and removing programs from an emulator or device.

The Dalvik Debug Monitor Server (DDMS)

The Dalvik Debug Monitor Server (DDMS) is a traffic director between the single port that
Eclipse (and other Java debuggers) looks for to connect to a Java Virtual Machine (JVM) and the
several ports that exist for each Android device or virtual device; DDMS is also a traffic
controller for each instance of the Dalvik virtual machine (VM) on each device. The DDMS also
provides a collection of functionality that is accessible through a standalone user interface or
through an interface embedded in Eclipse via the ADT plug-in.

When you invoke the DDMS from the command line, you will see something similar to the
window shown below. The following figure shows the Dalvik Debug Monitor running in
standalone mode.

123
Android Lab Manual for Novice

The DDMS’s user interface provides access to the following:

A list of devices and virtual devices, and the VMs running on those devices

In the upper-left pane of the DDMS window, you will see listed the Android devices you
have connected to your PC, plus any AVDs you have running. Listed under each device
or virtual device are the tasks running in Dalvik VMs.

VM information

Selecting one of the Dalvik VMs running on a device or virtual device causes information
about that VM to be displayed in the upper-right pane.

124
Android Lab Manual for Novice

Thread information

Information for threads within each process is accessed through the Threads tab in the
upper-right pane of the DDMS window.

Filesystem explorer

You can explore the filesystem on a device or virtual device using the DDMS filesystem
explorer, accessible through the “File explorer” menu item in the Devices menu. It
displays the file hierarchy in a window similar to the one shown above.

Simulating phone calls

The Emulator Control tab in the upper-right pane of the DDMS window enables you to
‘fake’ a phone call or text message in an emulator.

Screen capture

The ‘Screen capture’ command in the Device menu fetches an image of the current
screen from the selected Android device or virtual device.

Logging

The bottom pane of the DDMS window displays log output from processes on the
selected device or virtual device. You can filter the log output by selecting a filter from
among the buttons on the toolbar above the logging pane.

Dumping state for devices, apps, and the mobile radio

A set of commands in the Device menu enables you to command the device or virtual
device to dump state for the whole device, an app, or the mobile radio.

The following figure shows the DDMS filesystem explorer.

125
Android Lab Manual for Novice

Components of the ADT Eclipse Plug-in

Eclipse enables you to create specific project types, including several kinds of Java projects. The
ADT plug-in adds the ability to make and use Android projects. When you make a new Android
project, the ADT plug-in creates the project file hierarchy and all the required files for the
minimal Android project to be correctly built. For Android projects, the ADT plug-in enables
Eclipse to apply components of the ADT plug-in to editing, building, running, and debugging
that project.

In some cases, components of the SDK can be used with Eclipse or in a standalone mode. But in
most of the Android application development cases covered in this book, the way these
components are used in or with Eclipse will be the most relevant.

The ADT plug-in has numerous separate components, and, despite the connotations of a “plug-
in” as a modest enhancement, it’s a substantial amount of software. Here we will describe each

126
Android Lab Manual for Novice

significant part of the ADT plug-in that you will encounter in using Eclipse for developing
Android software.

The Android Layout Editor

Layouts for user interfaces in Android applications can be specified in XML. The ADT plug-in
adds a visual editor that helps you to compose and preview Android layouts. When you open a
layout file, the ADT plug-in automatically starts this editor to view and edit the file. Tabs along
the bottom of the editing pane enable you to switch between the visual editor and an XML editor.

In earlier versions of the Android SDK, the Android Layout Editor was too limited to be of much
use. Now, though, you should consider using visual editing of Android layouts as a preferred
way of creating layouts. Automating the specification of layouts makes it more likely that your
layouts will work on the widest range of Android devices.

The Android Manifest Editor

In Android projects, a manifest file is included with the project’s software and resources when
the project is built. This file tells the Android system how to install and use the software in the
archive that contains the built project. The manifest file is in XML, and the ADT plug-in
provides a specialized XML editor to edit the manifest.

Other components of the ADT Eclipse plug-in, such as the application builders, can also modify
the manifest.

XML editors for other Android XML files

Other Android XML files that hold information such as specifications for menus or resources
such as strings, or that organize graphical assets of an application, have specialized editors that
are opened when you open these files.

127
Android Lab Manual for Novice

Building Android apps

Eclipse projects are usually built automatically. That means you will normally not encounter a
separate step for turning the source code and resources for a project into a deployable result.
Android requires Android-specific steps to build a file you can deploy to an Android emulator or
device, and the ADT plug-in provides the software that executes these steps. For Android
projects, the result of building the project is an .apk file. You can find this file for the test project
created earlier in this chapter in the bin subfolder of the project’s file hierarchy in your Eclipse
workspace.

The Android-specific builders provided in the ADT plug-in enable you to use Java as the
language for creating Android software, while running that software on a Dalvik VM that
processes its own bytecodes. That is, among other things these builders do, they turn the Java
bytecode output of the Java compiler into Dalvik bytecodes. They also create .apk files, which
have a different structure and content than .jar files.

Running and debugging Android apps

When you run or debug an Android project from within Eclipse, the .apk file for that project is
deployed and started on an AVD or Android device, using the adb and DDMS to communicate
with the AVD or device and the Dalvik runtime environment that runs the project’s code. The
ADT plug-in adds the components that enable Eclipse to do this.

The DDMS

In The Dalvik Debug Monitor Server (DDMS) the Dalvik Debug Monitor was described and
how to invoke the DDMS user interface from the command line. The DDMS user interface is
also available from within Eclipse. You can access it by using the Window→Open
Perspective→DDMS command in the Eclipse menu. You can also access each view that makes
up the DDMS perspective separately by using the Window→Show View menu and selecting, for
example, the LogCat view.

128
Android Lab Manual for Novice

1.6.3 Introduction to Activity Manager

Android Virtual Devices

AVDs are made up of QEMU-based emulators that emulate the hardware of an Android device,
plus Android system images, which consist of Android software built to run on the emulated
hardware. AVDs are configured by the SDK and AVD Manager, which sets parameters such as
the size of emulated storage devices and screen dimensions, and which enables you to specify
which Android system image will be used with which emulated device.

AVDs enable you to test your software on a broader range of system characteristics than you are
likely to be able to acquire and test on physical devices. Because QEMU-based hardware
emulators, system images, and the parameters of AVDs are all interchangeable parts, you can
even test devices and system images before hardware is available to run them.

129
Android Lab Manual for Novice

QEMU

QEMU is the basis of AVDs. But QEMU is a very general tool that is used in a wide range of
emulation systems outside the Android SDK. While you will configure QEMU indirectly,
through the SDK and AVD Manager, you may someday need to tweak emulation in ways
unsupported by the SDK tools, or you may be curious about the capabilities and limitations of
QEMU.

The SDK and AVD Manager

QEMU is a general-purpose emulator system. The Android SDK provides controls over the
configuration of QEMU that make sense for creating emulators that run Android system images.
The SDK and AVD Manager provides a user interface for you to control QEMU-based AVDs.

Other SDK Tools

In addition to the major tools you are likely to use in the normal course of most development
projects, there are several other tools in the SDK, and those that are used or invoked directly by
developers are described here.

Hierarchy Viewer

The Hierarchy Viewer displays and enables analysis of the view hierarchy of the current activity
of a selected Android device. This enables you to see and diagnose problems with your view
hierarchies as your application is running, or to examine the view hierarchies of other
applications to see how they are designed. It also lets you examine a magnified view of the
screen with alignment guides that help identify problems with layouts.

Layoutopt

Layoutopt is a static analyzer that operates on XML layout files and can diagnose some problems
with Android layouts.

130
Android Lab Manual for Novice

Monkey

Monkey is a test automation tool that runs in your emulator or device. You invoke this tool using
another tool in the SDK: adb. Adb enables you to start a shell on an emulator or device, and
Monkey is invoked from a shell, like this:

adb shell monkey --wait-dbg -p your.package.name 500

This invocation of Monkey sends 500 random events to the specified application (specified by
the package name) after waiting for a debugger to be attached.

sqlite3

Android uses SQLite as the database system for many system databases and provides APIs for
applications to make use of SQLite, which is convenient for data storage and presentation.
SQLite also has a command-line interface, and the sqlite3 command enables developers to dump
database schemas and perform other operations on Android databases.

These databases are, of course, in an Android device, or they are contained in an AVD, and
therefore the sqlite3 command is available in the adb shell.

keytool

keytool generates encryption keys, and is used by the ADT plug-in to create temporary debug
keys with which it signs code for the purpose of debugging. In most cases, you will use this tool
to create a signing certificate for releasing your applications.

Zipalign

Zipalign enables optimized access to data for production releases of Android applications. This
optimization must be performed after an application is signed for release, because the signature
affects byte alignment.

131
Android Lab Manual for Novice

Draw 9-patch

A 9-patch is a special kind of Android resource, composed of nine images, and useful when you
want, for example, buttons that can grow larger without changing the radius of their corners.
Draw 9-patch is a specialized drawing program for creating and previewing these types of
resources.

android

The command named android can be used to invoke the SDK and AVD Manager from the
command line, as we described in the SDK installation instructions in The Android SDK. It can
also be used to create an Android project from the command line. Used in this way, it causes all
the project folders, the manifest, the build properties, and the ant script for building the project to
be generated.

132
Android Lab Manual for Novice

CHAPTER 2
Getting Acquainted With Android Basics

Must Know Stuff for Android Developer………………..

2.1 Basic Building Blocks of Android


Android Component
An android component is simply a piece of code that has a well defined life cycle e.g. Activity,
Receiver, Service etc.

The core building blocks or fundamental components of android are


 Activities
 Services
 Broadcast Receivers and
 Content Providers

Activity
An activity is a class that represents a single GUI screen and handles user interaction with the UI.

Launcher Activity
If the application consists of multiple activities, then one of them should be registered as an
activity that is displayed when the application is launched. Such an activity is referred to as
“Launcher Activity”. The user can then navigate from the launcher activity to other activities in
an application.

133
Android Lab Manual for Novice

Service
Service is a time consuming task which executes in a background without requiring user
interaction and does not have any GUI of its own. Service can continue to execute in the
background even if the application which has started it is destroyed. If the application starts a
service, it is the responsibility of the application to stop it before terminating.

Broad Cast Receivers


Broadcast receiver handles communication between Android OS and user applications. It
responds to broadcast messages from other applications or from OS.

Content Provider
Content Providers are used to share data between different Android applications.

AndroidManifest.xml
Manifest is an application configuration file indexing the basic building blocks of an application.
It is an XML configuration file with the name AndroidManifest.xml. It encapsulates the
following details:
 Name of the launcher activity
 Names of the basic building blocks such as activity, service, broadcast receiver and
content provider
 Application permissions etc.

It contains information about the different components making up an android application and
records activities (launcher activity), services, broadcast receivers, content providers, different
permissions required for application etc. The AndroidManifest.xml file contains information of
your package, including components of the application such as activities, services, broadcast
receivers, content providers etc.

134
Android Lab Manual for Novice

It performs some other tasks also:


 It is responsible to protect the application to access any protected parts by providing the
permissions.
 It also declares the android api that the application is going to use.
 It lists the instrumentation classes. The instrumentation classes provides profiling and
other information. These informations are removed just before the application is
published etc.
 This is the required xml file for all the android application and located inside the root
directory.

A simple AndroidManifest.xml file looks like this:

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.first_project"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.first_project.MainActivity"
android:label="@string/app_name" >

135
Android Lab Manual for Novice

<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>
</manifest>

2.2 Elements of the AndroidManifest.xml file


The elements used in the above xml file are described below:
<manifest>
manifest is the root element of the AndroidManifest.xml file. It has package attribute that
describes the package name of the activity class.

<application>
application is the sub-element of the manifest. It includes the namespace declaration. This
element contains several sub-elements that declares the application component such as activity
etc.
The commonly used attributes are of this element are icon, label, theme etc.
android:icon represents the icon for all the android application components.
android:label works as the default label for all the application components.
android:theme represents a common theme for all the android activities.

<activity>
activity is the sub-element of application and represents an activity that must be defined in the
AndroidManifest.xml file. It has many attributes such as label, name, theme, launchMode etc.
android:label represents a label i.e. displayed on the screen.
android:name represents a name for the activity class. It is required attribute.

136
Android Lab Manual for Novice

<intent-filter>
intent-filter is the sub-element of activity that describes the type of intent to which activity,
service or broadcast receiver can respond to.

<action>
It adds an action for the intent-filter. The intent-filter must have at least one action element.

<category>
It adds a category name to an intent-filter.

More of Android Terminology…

Intents
Intents are the messages connecting together different components of Android application.
Intents are used for invoking services both system level services and user-defined services. Few
actions performed by intents are:
 starting a new service
 Launching an activity
 Displaying a web page
 Broadcasting a message
 Dialing a phone call etc.

Resources
Resources are static data such as layouts, menus, bitmaps, layouts, colors, styles, strings, images
etc. which are organized in separate sub folders under /res sub folder of the android application
project folder as shown in the following figure .

137
Android Lab Manual for Novice

APK File
An apk file is created by the framework automatically. If you want to run the android application
on the mobile, transfer and install it. All the resources reside in different folders under ‘res’
folder of a project folder as depicted in the following figure:

The description of various resources employed in android application is depicted in Table.

Sr.No. Directory & Resource Type

1 anim/
XML files that define property animations. They are saved in res/anim/ folder
and accessed from the R.anim class.

2 color/
XML files that define a state list of colors. They are saved in res/color/ and
accessed from the R.color class.

138
Android Lab Manual for Novice

3 drawable/
Image files like .png, .jpg, .gif or XML files that are compiled into bitmaps, state
lists, shapes, animation drawable. They are saved in res/drawable/ and accessed
from the R.drawable class.

4 layout/
XML files that define a user interface layout. They are saved in res/layout/ and
accessed from the R.layout class.

5 menu/
XML files that define application menus, such as an Options Menu, Context
Menu, or Sub Menu. They are saved in res/menu/ and accessed from
the R.menu class.

6 raw/
Arbitrary files to save in their raw form. You need to
call Resources.openRawResource() with the resource ID, which
is R.raw.filename to open such raw files.

7 values/
XML files that contain simple values, such as strings, integers, and colors. For
example, here are some filename conventions for resources you can create in this
directory −
 arrays.xml for resource arrays, and accessed from the R.array class.
 integers.xml for resource integers, and accessed from the R.integer class.
 bools.xml for resource boolean, and accessed from the R.bool class.
 colors.xml for color values, and accessed from the R.color class.
 dimens.xml for dimension values, and accessed from the R.dimen class.
 strings.xml for string values, and accessed from the R.string class.
 styles.xml for styles, and accessed from the R.style class.

139
Android Lab Manual for Novice

8 xml/
Arbitrary XML files that can be read at runtime by calling Resources.getXML().
You can save various configuration files here which will be used at run time.

Views
Views are the UI elements drawn on the container.

Widgets
Widgets are the controls placed on the home screen of an Android application.

Fragments
Fragments represent the portion of UI in an activity. A fragment is a kind of sub-activity. An
activity can be divided into different sub-activities where each sub-activity is represented by a
fragment. An activity can display one or more fragments on the screen at the same time.

Layouts
Layouts control the organization of widgets on the container.

R Class
When the Android application is compiled, R class gets automatically generated, which
contains resource IDs for all the resources available in res/ sub-folder of a project folder. R class
can be used to access the resource using sub-directory and resource name or directly resource
ID.
It is the auto-generated file that contains IDs for all the resources of res directory. It is generated
by aapt(Android Asset Packaging Tool). Whenever you create any component on activity_main,
a corresponding ID is created in the R.java file which can be used in the Java Source file later.

140
Android Lab Manual for Novice

If you create any component in the activity_main.xml file, id for the corresponding component is
automatically created in this file. This id can be used in the activity source file to perform any
action on the component.

R.java file includes a lot of static nested classes such as menu, id, layout, attr, drawable, string
etc.

2.3 Structure of R Class


The structure of auto generated R class is depicted below:

/* AUTO-GENERATED FILE. DO NOT MODIFY.


*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/

package com.example.launcher;

public final class R {


public static final class attr {
}

public static final class dimen {


/** Default screen margins, per the Android Design guidelines.

Customize dimensions originally defined in res/values/dimens.xml (such as


screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.

*/

141
Android Lab Manual for Novice

public static final int activity_horizontal_margin=0x7f040000;


public static final int activity_vertical_margin=0x7f040001;
}

public static final class drawable {


public static final int ic_launcher=0x7f020000;
}

public static final class id {


public static final int RelativeLayout1=0x7f080000;
public static final int action_settings=0x7f080003;
public static final int imageView1=0x7f080002;
public static final int textView1=0x7f080001;
}

public static final class layout {


public static final int activity_main=0x7f030000;
public static final int activity_second=0x7f030001;
}
public static final class menu {
public static final int main=0x7f070000;
}

public static final class string {


public static final int action_settings=0x7f050001;
public static final int app_name=0x7f050000;
public static final int hello_world=0x7f050002;
}

public static final class style {


/**

142
Android Lab Manual for Novice

Base application theme, dependent on API level. This theme is replaced


by AppBaseTheme from res/values-vXX/styles.xml on newer devices.

Theme customizations available in newer API levels can go in


res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.

Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.

API 11 theme customizations can go here.


Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.

API 14 theme customizations can go here.


*/
public static final int AppBaseTheme=0x7f060000;
/** Application theme.

All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
}
}

As evident from the structure of R class, there is a nested class corresponding to each subfolder
contained under /res sub-folder of the android project folder.

143
Android Lab Manual for Novice

The syntax employed for accessing different resources contained in /res folder in both java
program and XML file using the resource name is shown in the following table:

Accessing this Resource Folder Do this in


Containing the
Resource
Java Code XML File
String /res/values/strings R.string.<name> @string/<name>
String Array /res/values/strings R.array.<name> @array/<name>
Images /res/drawable R.drawable.<name> @drawable/<name>
Layout /res/layout R.layout.<name> @layout/<name>
color /res/color R.color.<name> @color/<name>
Widget R.id.<name> @id/<name>

2.4 Core Android Libraries for Android Developers


The following table depicts the important Android packages required for development of
Android application.

Package Description
android.app Provides access to the application model and is the cornerstone
of all Android applications
android.content Facilitates content access, and messaging between applications
and application components.
android.os Provides applications with access to standard operating system
services including messages, system services and inter-process
communication.
android.view The fundamental building blocks of application user
interfaces.
android.view.View Listener interfaces for event handling.

144
Android Lab Manual for Novice

android.widget A rich collection of pre-built user interface components such as


buttons, labels, list views, layout managers, radio buttons etc.

android.text Used to render and manipulate text on a device display.

android.database Used to access data published by content providers and


includes SQLite database management classes.

Packages Required in Minimal Android Application


A minimal Android application requires the packages given below:
1. android.app → for Activity class
2. android.os → for Bundle class
3. android.view → for Menu class (if menu is required)
4. android.widget → for adding controls to the layout (such as TextView control).

Package Name Classes in the Package


android.os Bundle
android.app Activity
android.view Menu

2.5 Anatomy of Android Application


Structure of MainActivity Class

The structure of the MainActivity class generated by Eclipse is shown below:

package com.example.helloandroid;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

145
Android Lab Manual for Novice

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

The onCreate() method of Activity class is called when Activity class is first created. onCreate()
method is the first method of the activity life cycle methods which has the following prototype:

protected void onCreate(Bundle savedInstanceState)

The overridden onCreate() method of MainActivity class performs the following two tasks;
1. Invokes super class onCreate() method.
2. Invokes setContentView() method for laying controls on layout. The setContentview()
method inflates the XML layout file and instantiates the objects and renders the layout.

R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder.


setContentView() method accepts a single parameter, ‘R.layout.activity_main’ where,
‘activity_main’ is the name of the XML file containing layout information which is located in
the folder res/layout in the project folder.

146
Android Lab Manual for Novice

The structure of ‘activity_main.xml’ file is shown below:

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"/>
</RelativeLayout>

Launcher Activity Class in Android


Activity is a java class that creates a default window on the screen which is a container for
different components such as Button, EditText, etc. It is the launcher activity which is registered
in AndroidManifest.xml file as shown below:

<activity android:name="com.example.helloandroid.MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

147
Android Lab Manual for Novice

Bundle in Android`
Bundle is a class used for sharing data between different android activities. Bundle is a custom
Android hash map. It is commonly employed to preserve the activity’s data when the activity
gets destroyed (such as when its orientation gets changed) using key/value pair and retrieve back
and display when the activity is created again. The key allows the data to be retrieved back from
the Bundle.

Referring to String Resource in XML File


Strings.xml File
The ‘strings.xml’ file is located in the res/values folder and it contains all the text that android
application uses. For example, the captions of buttons, labels, default text etc. are contained in
this file. This file encapsulates the textual content.
The structure of res/values/string.xml file is shown below:
<?xml version="1.0"encoding="utf-8"?>
<resources>
<string name="app_name">HelloAndroid</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>

In order to refer to any resource in ‘strings.xml’ file employ the syntax given below:
@string/<name>
Where, <name> is the name of the string resource.
For example, to refer to string resource with the name app_name use the syntax,
@string/app_name.

But the message for this string is defined in the ‘strings.xml’ file. The
@string/hello_world provides information about the textview message. The value of the
attribute hello_world is defined in the ‘strings.xml’ file.

148
Android Lab Manual for Novice

Layout File
The ‘activity_main.xml’ is a layout file available in res/layout directory which is referenced by
your application during building its interface. This file is modified very frequently to change the
layout of the application. The content of the file corresponding to default layout is shown
below:
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity"/>
</RelativeLayout>

This is an example of simple RelativeLayout. The TextView is an Android control used to build
the GUI and it have various XML attributes
like android:layout_width, android:layout_height etc. which are being used to set its width and
height etc.. The @string refers to the strings.xml file located in the res/values folder. Hence,
@string/hello_world refers to the hello string defined in the ‘strings.xml’ file, which is "Hello
World!".
On double-clicking the layout file, activity_main.xml in package explorer, it is opened in the
default editor. The editor has two views:
1. Graphical View
2. Text View

149
Android Lab Manual for Novice

Graphical Layout

Viewing Source of activity_main.xml File

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

150
Android Lab Manual for Novice

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

</RelativeLayout>

Inflating the XML Layout


Inflating the XML file refers to parsing the XML file, creating the view objects in memory and
rendering the view objects on layout. Inflating a view means taking the layout XML and parsing
it to create the view and viewgroup objects from the elements and their attributes specified
within, and then adding the hierarchy of those views and viewgroups to the parent ViewGroup.
When you call setContentView(), it attaches the views it creates from reading the XML to the
activity.
Inflating the layout is performed by android OS, hence it is referred to as implicit inflation.
You can also inflate views explicitly by using the LayoutInflater. In that case you have to:
1. Get an instance of the LayoutInflater
2. Specify the XML to inflate
3. Use the returned View

Example:
The code for creating a view by inflating the layout is shown below:

LayoutInflater inflater = LayoutInflater.from(MainActivity.this);


View v = inflater.inflate(R.layout.layout_name, null);

Auto Generated R.java file


It is the auto-generated file that contains IDs for all the resources of res directory. It is generated
by aapt(Android Asset Packaging Tool). Whenever you create any component on activity_main,
a corresponding ID is created in the R.java file which can be used in the Java Source file later.

151
Android Lab Manual for Novice

/* AUTO-GENERATED FILE. DO NOT MODIFY.


*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/

packagecom.example.hello;

public final class R {


public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.

Customize dimensions originally defined in res/values/dimens.xml (such as


screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.

*/
public static final intactivity_horizontal_margin=0x7f040000;
public static final intactivity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final intic_launcher=0x7f020000;
}
public static final class id {
public static final intaction_settings=0x7f080000;
}
public static final class layout {
public static final intactivity_main=0x7f030000;
}

152
Android Lab Manual for Novice

public static final class menu {


public static final int main=0x7f070000;
}
public static final class string {
public static final intaction_settings=0x7f050001;
public static final intapp_name=0x7f050000;
public static final inthello_world=0x7f050002;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
byAppBaseTheme from res/values-vXX/styles.xml on newer devices.

Theme customizations available in newer API levels can go in


res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.

Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.

API 11 theme customizations can go here.

Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.

API 14 theme customizations can go here.


*/
public static final intAppBaseTheme=0x7f060000;

153
Android Lab Manual for Novice

/** Application theme.


All customizations that are NOT specific to a particular API-level can go here.
*/
public static final intAppTheme=0x7f060001;
}
}

APK File
An apk file is created by the framework automatically. If you want to run the android application
on the mobile, transfer and install it.

Manifest file
It contains information about package including components such as activities, services, content
providers etc.

AndroidManifest.xml file in android


The AndroidManifest.xml file contains information of your package, including components of
the application such as activities, services, broadcast receivers, content providers etc.
It performs some other tasks also:
o It is responsible to protect the application to access any protected parts by providing the
permissions.
o It also declares the android api that the application is going to use.
o It lists the instrumentation classes. The instrumentation classes provides profiling and
other informations. These informations are removed just before the application is
published etc.
This is the required xml file for all the android application and located inside the root directory.

Obtaining Reference to Controls in Java Code


The MainActivity class inherits a method with the name findViewById() which accepts the ID of
the control and returns reference to the control stored in ‘View’ class which should be cast to the

154
Android Lab Manual for Novice

appropriate control class before accessing the properties. When the control is added to the layout,
the corresponding entry is created in R.java class which maps a control to the unique numeric ID.
The ID generated in R class can be accessed using the following syntax:
R.id.<control_name>
The above ID should be passed to findViewById() for obtaining reference to the control.

Example 1:
Suppose a layout contains a text view control with the ID ‘textView1’. The reference to the text
view control can be obtained using the following code:

TextView t = (TextView) findViewById(R.id.textView1);

Example 2:
Suppose a layout contains two edit text controls with the IDs ‘editText1’ and ‘editText2’. The
reference to the edit text controls can be obtained in java code using the following code:

EditText e1 = (EditText) findViewById(R.id.editText1);


EditText e2 = (EditText) findViewById(R.id.editText2);

The same logic can be applied for obtaining reference to other controls present on the layout.

Program : Changing the Text Displayed in TextView Control


1. Create a new Android application project with the name ‘hello’. The structure of
‘MainActivity’ class is shown below:

MainActivity.java

package com.example.hello;
import android.os.Bundle;

155
Android Lab Manual for Novice

import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

2. In the design view or text view change the ‘Text’ property of ‘textView1’ control to
‘Hello Android’.

The structure of ‘activity_main.xml’ file is shown below:


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"

156
Android Lab Manual for Novice

android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="150dp"
android:text="Hello Android"
android:textColor="#0000ff"
android:textSize="25sp" />
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

157
Android Lab Manual for Novice

Execution of the application in Android Studio


 Launch Android Studio
 Create a new project with the name ‘HelloAndroid’ containing empty activity.
 Click on ‘activity_main.xml’ tab and change the ‘Text’ property of TextView control to
‘Hello Android’.

For changing the text size and color, click on ‘View all properties’ link at the bottom of
‘Properties’ window to display additional properties. The properties are organized in the
alphabetical order of their names. Scroll down to text properties and change the ‘textColor’
property to ‘#0000ff’ and ‘textSize’ property to ‘24sp’ as shown in the following figure:

158
Android Lab Manual for Novice

Execute the application by pressing the key combination, Shift + F10 or by clicking on a tool
representing green left pointing triangle.

Select the virtual device ‘siber’ as the deployment target as shown in the following figure:

159
Android Lab Manual for Novice

The following output is generated:

2.6 Displaying a Message in Android - Toast Class


‘android.widget’ package contains a class with the name ‘Toast’ which can be used for
displaying a message.
• Android Toast can be used to display information for the short period of time. A toast
contains message to be displayed quickly and disappears after sometime.
• The ‘android.widget.Toast’ class is the subclass of ‘java.lang.Object’ class.
• Toast class is used to show notification for a particular interval of time. After sometime it
disappears. It doesn't block the user interaction.

Constants of Toast class


There are only 2 constants of Toast class which are given below.

160
Android Lab Manual for Novice

Constant Description
public static final int LENGTH_LONG Displays message for a long duration
public static final int LENGTH_SHORT Displays message for a short duration

Methods of Toast class


The widely used methods of Toast class are given below.

Method Name Description


public static Toast makeText(Context context, Creates an instance of Toast class with the
CharSequence text, int duration) specified text and duration.
public void show() Displays a message contained in a Toast
public void setMargin(float horizontalMargin, Sets the horizontal and vertical margin for the
float verticalMargin) Toast

Displaying a message using Toast is a two step process:


1. Create an instance of ‘Toast’ by invoking its static method makeText() which accepts
three arguments.
a. The first argument is a Context reference.
b. The second argument is a message to be displayed and
c. The third argument is a constant specifying the length if duration of the message,
which can be one of
i. Toast.LENGTH_LONG or
ii. Toast.LENGTH_SHORT

2. Display the message by invoking show() method of ‘Toast’ class.

The code for the same is shown below:


Toast t = Toast.makeText(MainActivity.this, “Hello Android”, Toast.LENGTH_LONG);
t.show();

161
Android Lab Manual for Novice

Alternately, the two statements can be combined into a single statement as shown below:
Toast.makeText(MainActivity.this, “Hello Android”, Toast.LENGTH_LONG).show();

1. Create a new Android application project with the name ‘toast_demo’.


2. Append the following statements in onCreate() method of MainActivity class as shown
below:
Toast t = Toast.makeText(MainActivity.this, “Hello Android”, Toast.LENGTH_LONG);
t.show();
3. The error message ‘Toast cannot be resolved’ is displayed. Hover the mouse on the word
containing error (underlined with red wavy line). Quick fixes are displayed as shown in
the following figure. From the list select the first quick fix.

The structure of ‘MainActivity’ class is shown below:

162
Android Lab Manual for Novice

MainActivity.java

package com.example.toast_demo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast t = Toast.makeText(MainActivity.this, "Hello Android",
Toast.LENGTH_LONG);
t.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

4. Select the project in the package explorer and select Project → Build Project from the
main menu as shown in the following figure:

163
Android Lab Manual for Novice

5. Start the Emulator.

6. Execute the application, by selecting the project in package explorer and selecting Run
As → Android Application from the shortcut menu as shown below:

164
Android Lab Manual for Novice

On deploying the project in the emulator, the following output is generated:

165
Android Lab Manual for Novice

Execution of the application in Android Studio


1. Create a new project with the name “HelloAndroid”.
2. Change the ‘Text’ property of TextView control to ‘Toast Demo’.
3. Change the ‘textSize’ property to ‘24sp’.
4. Change the ‘textColor’ property to ‘#0000ff’.

Deploy the application on a target device. The following output is generated:

2.7 Event Handling in Android


There are three distinct methods of handling click event in Android
 Declarative Event Handling by adding ‘android:onClick’ XML attribute to Button
element.
 By implementing ‘OnClickListener’ interface.

166
Android Lab Manual for Novice

 Using Anonymous Inner class.

The following sections explore the three different methods of handling click event in Android.

Method 1: Declarative Event Handling


In the declarative event handling, ‘android:onClick’ attribute of button element in layout XML
file is set to the method handling the click event for the button. This is illustrated in the following
program.

Program : Handling Click Event of a Button Using Declarative Event


Handling
1. Create a new Android application project with the name ‘hello1’.
2. Place a button control on the layout and change it’s ‘Text’ property to ‘Click Me’
3. Add a method to MainActivity class with the name sayHello() as shown below:

public void sayHello(View v)


{
Toast t = Toast.makeText(this, "Hello Android!", Toast.LENGTH_LONG);
t.show();
}

The structure of ‘MainActivity’ class is shown below:

MainActivity.java

package com.example.hello1;
import android.os.Bundle;
import android.app.Activity;

167
Android Lab Manual for Novice

import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

public void sayHello(View v)


{
Toast t = Toast.makeText(this, "Hello Android!", Toast.LENGTH_LONG);
t.show();
}
}

4. Add the following attribute to <button> element in activity_main.xml file.


android:onClick="sayHello"

The structure of activity_main.xml file is shown below:

168
Android Lab Manual for Novice

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="105dp"
android:layout_marginTop="173dp"
android:gravity="top"
android:onClick="sayHello"
android:text="Click Me" />
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

169
Android Lab Manual for Novice

On clicking the ‘Click Me’ button, the following output is generated;

170
Android Lab Manual for Novice

Execution of Application in Android Studio


Declarative Event Handling in Android Studio
For adding event handler to click event of a button in activity_main.xml file declaratively in
Android Studio follow the steps enumerated below:
1. Double–click on the button in design view.
2. Click on the drop-down list next to ‘onClick’ property.
3. From the list of methods displayed, select the required method.

4. Remove the class name displayed in brackets as shown below:

5. The following attribute is added to button element in ‘activity_main.xml’ file.


android:onClick=”next”
as shown below:

171
Android Lab Manual for Novice

On execution of the application in Android Studio the following output is generated:

172
Android Lab Manual for Novice

Click on ‘Click Me’ button. The message ‘Hello Android’ is displayed in a Toast as shown in
the following figure:

173
Android Lab Manual for Novice

1. Create a new project with the name ‘button_click’.


2. Change the ‘Text’ property of Button control to ‘Click Me’.
3. Open the ‘activity_main.xml’ file in design view.
4. Double-click on the button control and in the properties sheet, set the ‘onClick’ attribute
of button control to ‘sayHello’ as shown in the following figure:

5. Add sayHello() method to MainActivity class as described earlier.


6. Deploy the application on target device.

The following output is generated on clicking ‘CLICK ME’ button:

174
Android Lab Manual for Novice

Program:

1. Create a new Android application project with the name ‘hello4’. The structure of
‘MainActivity’ class is shown below:

2. Add a method to MainActivity class with the name sayHello() as shown below:

public void display(View v)


{
t.setText("Hello Android!");
}

175
Android Lab Manual for Novice

MainActivity.java

package com.example.hello4;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {


TextView t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(TextView)findViewById(R.id.textView1);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void display(View v)
{
t.setText("Hello Android!");
}
}

On deploying the project in the emulator, the following output is generated:

176
Android Lab Manual for Novice

Execution of the Application in Android Studio


1. Create a new project with the name ‘button_click’.
2. Change the ‘Text’ property of Button control to ‘Say Hello’.
3. Open the ‘activity_main.xml’ file in design view.
4. Double-click on the button control and in the properties sheet, set the ‘onClick’ attribute
of button control to ‘display’.
5. Declare the following variable in ‘MainActivity’ class.
TextView t;
Add import by placing the mouse on ‘TextView’ and pressing the key combination, Alt +
Enter.
6. Initialize the variable in onCreate() method of MainActivity class. Add type cast by
selecting the appropriate item from the suggestion list.

177
Android Lab Manual for Novice

7. Implement the display() method in MainActivity class as described above.


8. Deploy the application on target device.

The following output is generated on clicking ‘CLICK ME’ button:

178
Android Lab Manual for Novice

Event Handling – An Alternate Method


android.view.View package contains all the listener interfaces used in event handling.
OnClickListener interface is used for processing click events generated by a button.
To process click event of a button by implementing OnClickListener interface follow the steps
given below:
1. Modify ‘MainActivity’ class to implement ‘OnClickListener’ interface.
2. Register the MainActivity class with the button generating the click event to receive the
notification.
3. Implement onClick() method in MainActivity class.

Program:
1. Create a new Android application project with the name ‘hello2’.
2. Place a Button control on the layout as shown below and set its Text property to ‘Click
Me’.
3. Modify the MainActivity class as shown below:

The complete source code listing of MainActivity class is given below:

MainActivity.java

package com.example.hello2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

179
Android Lab Manual for Novice

Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public void onClick(View arg0) {
Toast t=Toast.makeText(MainActivity.this, "Hello android!",
Toast.LENGTH_LONG);
t.show();
}
}

On clicking the button, the same output as in above program is generated.

Execution of the Application in Android Studio


Adding Unimplemented methods in Android Studio

The code generated in Android Studio is shown in the following figure:

180
Android Lab Manual for Novice

First add import to ‘OnClickListener’ interface as shown below:

As shown in the above figure, there are two declarations of ‘OnClickListener’ interface, one
declaration is present in ‘android.view.View’ package and another declaration is present in,
‘android.content.DialogInterface’. Select the first option from the list displayed.

Note: The shortcut key for displaying the hint is placing the mouse on the text containing the
error (displayed in red) and pressing the key combination, Alt+Enter.

181
Android Lab Manual for Novice

From the hint displayed, select the option ‘Implement methods’. The following dialog is
displayed. Select the method and click on ‘OK’ button.

The ‘onClick’ method is added to MainActivity class as shown below:

182
Android Lab Manual for Novice

Program :
Handling Click Event of a Button Using Anonymous Inner Class
1. Create a new Android application project with the name ‘hello2’.
2. Place an edit text control and a button control on the layout
3. Change the ‘Text’ property of a button control to ‘Say Hello’

The structure of ‘MainActivity’ class is shown below:


MainActivity.java

package com.example.hello2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

183
Android Lab Manual for Novice

public class MainActivity extends Activity {


EditText t;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(EditText)findViewById(R.id.editText1);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
t.setText("Hello Android!");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

The structure of activity_main.xml file is shown below:


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

184
Android Lab Manual for Novice

android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="Say Hello" />
</RelativeLayout>

On deploying the project in the emulator and clicking on ‘Say Hello’ button, the following
output is generated:

185
Android Lab Manual for Novice

Program : Android Program to Illustrate Event Handling – Using


Anonymous Inner Class
1. Create a new Android application project with the name ‘hello3’.
2. Place a Button control on the layout as shown below and set its ‘Text’ property to ‘Click
Me’.
3. Modify the MainActivity class as shown below:

The complete source code listing of MainActivity class is given below:


MainActivity.java

package com.example.hello3;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;

186
Android Lab Manual for Novice

import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {


Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0) {
Toast t=Toast.makeText(MainActivity.this, "Hello android!",
Toast.LENGTH_LONG);
t.show();
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

On clicking the ‘Click Me’ button, the following output is generated:

187
Android Lab Manual for Novice

Program : Android Program to Illustrate Handling Multiple Buttons


The reference to the ‘View’ class passed to the click event handler as an argument contains the
information about the button widget generating the event. The Id of the button generating the
event can be obtained by invoking getId() method on View object.
The following program generates two different messages depending on the button clicked by the
user.
1. Create a new Android application project with the name ‘buttons’.
2. Place two Button controls on the layout and set their Text property to ‘MCA’ and ‘MBA’.
3. Open activity-main.xml file in text editor and add android:onClick attribute to both the
button elements as shown below:

android:onClick="displayMessage"

188
Android Lab Manual for Novice

4. Add displayMessage() method to MainActivity class as shown below:

public void displayMessage(View v)


{
switch(v.getId())
{
case R.id.button1 :
Toast.makeText(this, "Hello MCA!", Toast.LENGTH_LONG).show();
break;
case R.id.button2 :
Toast.makeText(this, "Hello MBA!", Toast.LENGTH_LONG).show();
break;
}
}

The complete source code listing of MainActivity class is given below:


activity_main.xml

package com.example.buttons;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

189
Android Lab Manual for Novice

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

public void displayMessage(View v)


{
switch(v.getId())
{
case R.id.button1 :
Toast.makeText(this, "Hello MBA!", Toast.LENGTH_LONG).show();
break;
case R.id.button2 :
Toast.makeText(this, "Hello MCA!", Toast.LENGTH_LONG).show();
break;
}
}
}

The structure of activity_main.xml layout file is shown below:


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"

190
Android Lab Manual for Novice

android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="36dp"
android:layout_marginTop="57dp"
android:text="MCA"
android:onClick="displayMessage" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_marginLeft="34dp"
android:layout_toRightOf="@+id/button1"
android:text="MBA"
android:onClick="displayMessage" />
</RelativeLayout>

Deploy the application on the emulator. On clicking button with the text ‘MCA’, the following
output is generated.

191
Android Lab Manual for Novice

Execution of the Application in Android Studio


On executing the application in Android Studio, the following output is generated:

192
Android Lab Manual for Novice

Click on button with caption ‘MBA’. The message ‘Hello MBA!’ is displayed as shown in the
following figure:

Now, click on button with caption ‘MCA’. The message ‘Hello MCA!’ is displayed as shown in
the following figure:

193
Android Lab Manual for Novice

2.8 Writing Messages to Application Log in Android


Log class present in ‘java.util’ package provides a handy way of displaying messages,
intermediate values of variables which facilitates debugging of android application. The class has
several methods for writing informative, debug, error messages to application log. All these
methods accept two parameters, first parameter is the group name of the message and the second
parameter is the message. The log messages can be filtered based on the group name when the
large no. of messages are generated.

Debug messages are displayed in blue color. Informative messages are displayed in green color
and error messages are displayed in red color.

The following tabled depicts the different methods of Log class for displaying messages of
different severity.
Method Name Description
d Writing debug messages to application log.
i Writing informative messages to application log.
e Writing error messages to application log.

Program : Android Program to Illustrate Writing to Application Log.


The following android application demonstrates displaying messages in application log.

1. Create a new Android application project with the name ‘logfile’.

The complete source code listing of MainActivity class is given below:

MainActivity.java

package com.example.logfile;

194
Android Lab Manual for Novice

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("MainActivity", "Inside Create Method");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Execute the application and click on the LogCat tab. Monitor the Tag corresponding to
‘MainActivity’ displaying the message.

195
Android Lab Manual for Novice

Execution of the Application in Android Studio


Execute the above application in Android Studio without any modification.

On deploying the application on target device, click on ‘Android monitor’ tab at the bottom and
click on ‘logcat’ tab.

In the search field, enter ‘MainActivity’ as shown in the following figure:


The log message is listed as shown below:

Modify the MainActivity class as shown below:

MainActivity.java

package com.example.log_messages;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

@Override

196
Android Lab Manual for Novice

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Group1", "First Debug Messge in Group1");
Log.d("Group1", "Second Debug Messge in Group1");
Log.d("Group2", "First Debug Messge in Group2");
Log.d("Group2", "Second Debug Messge in Group2");

Log.e("Group1", "First Error Messge in Group1");


Log.e("Group1", "Second Error Messge in Group1");
Log.e("Group2", "First Error Messge in Group2");
Log.e("Group2", "Second Error Messge in Group2");

Log.i("Group1", "First Informative Messge in Group1");


Log.i("Group1", "Second Informative Messge in Group1");
Log.i("Group2", "First Informative Messge in Group2");
Log.i("Group2", "Second Informative Messge in Group2");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

On deploying the application in the emulator, the following output is generated on selecting
‘error’ from drop-down list:

197
Android Lab Manual for Novice

On selecting ‘debug’ and ‘info’ from drop-down list the output generated is shown below:

Creating Message Filter


The message filter can be set in eclipse for viewing only the messages belonging to a certain
group.

198
Android Lab Manual for Novice

Click on ‘Display Saved Filters View’ button located at the right corner as shown in the above
figure. ‘Saved Filters’ view is displayed as shown in the figure.
Click on green ‘+’ button to create a new filter. You can create the log filter based on one of the
following criterion:
 Log Tag
 Log Message
 PID
 Application Name and
 Log Event
as shown in the following figure:
Enter the Tag Name as ‘Group1’ to filter the messages belonging to ‘Group1’.

Similarly create ‘Group2’ filter containing the messages with the tag ‘Group2’.

199
Android Lab Manual for Novice

Execution of the Application in Android Studio


Execute the above application in Android Studio without any modification.
On deploying the application on target device, click on ‘Android monitor’ tab at the bottom and
click on ‘logcat’ tab.

Clearing a logcat Window


For clearing the logcat window, right-click in the window and select ‘Clear All’ option from the
shortcut menu as shown in the following figure:

Enter ‘Group’ in the search field and select ‘Error’ from the drop-down list as shown in the
following figure. The following output is generated:

On selecting ‘info’ from the drop-down list, the following output is generated:

200
Android Lab Manual for Novice

On selecting ‘debug’ from the drop-down list, the following output is generated:

Program : Android Program to Illustrate Displaying Text in Different


Color, Size and Alignment in Android

The TextView control provides several methods for changing the attributes of a text displayed by
it such as text color, text size, text alignment etc. as depicted in the following table:

Method Name Description


setTextColor() This method is used for specifying the color of
the text and accepts a single argument, the
constant defined in the android.graphics.Color
class.
setTextSize() This method is used for specifying the size of
the text in points.
setGravity() This method is used for specifying the text
alignment and accepts a single parameter a
constant defined in the android.view.Gravity
class.

The following Android program demonstrates these methods.


1. Create a new Android application project with the name ‘color’.
2. Append the following code to onCreate() method of MainActivity class:

201
Android Lab Manual for Novice

t1=(TextView)findViewById(R.id.textView1);
t1.setTextColor(Color.RED);
t1.setGravity(Gravity.CENTER);
t1.setTextSize(0, 24);
t1.setText("Center");

t2=(TextView)findViewById(R.id.textView2);
t2.setTextColor(Color.GREEN);
t2.setGravity(Gravity.LEFT);
t2.setTextSize(0, 36);
t2.setText("Left");

t3=(TextView)findViewById(R.id.textView3);
t3.setTextColor(Color.BLUE);
t3.setGravity(Gravity.RIGHT);
t3.setTextSize(0, 48);
t3.setText("Right");

The complete source code of MainActivity class is shown below:

MainActivity.java

package com.example.color;
import android.os.Bundle;
import android.widget.*;
import android.graphics.*;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;

202
Android Lab Manual for Novice

public class MainActivity extends Activity {


TextView t1,t2,t3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.textView1);
t1.setTextColor(Color.RED);
t1.setGravity(Gravity.CENTER);
t1.setTextSize(0, 24);
t1.setText("Center");

t2=(TextView)findViewById(R.id.textView2);
t2.setTextColor(Color.GREEN);
t2.setGravity(Gravity.LEFT);
t2.setTextSize(0, 36);
t2.setText("Left");

t3=(TextView)findViewById(R.id.textView3);
t3.setTextColor(Color.BLUE);
t3.setGravity(Gravity.RIGHT);
t3.setTextSize(0, 48);
t3.setText("Right");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

203
Android Lab Manual for Novice

The structure of activity_main.xml layout file is shown below:


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"
android:text="TextView" />

<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="75dp"
android:text="TextView" />

204
Android Lab Manual for Novice

<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="86dp"
android:text="TextView" />
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

Execution of the Application in Android Studio

On execution of the application in Android Studio, the following output is generated:

205
Android Lab Manual for Novice

Program : Android Program to Compute the Sum of Two Numbers


The following Android application demonstrates using EditText control.

1. Create a new Android application project with the name ‘add’.

2. Place three plain text controls (located in TextFields tab) and a button control (located in
Form Widgets tab) on the layout.

3. Declare the following control variables in MainActivity class.

EditText e1,e2,e3;
Button b;

206
Android Lab Manual for Novice

4. Append the following code to onCreate() method of MainActivity class:

e1=(EditText)findViewById(R.id.editText1);
e2=(EditText)findViewById(R.id.editText2);
e3=(EditText)findViewById(R.id.editText3);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
int n1=Integer.parseInt(e1.getText().toString());
int n2=Integer.parseInt(e2.getText().toString());
int sum=n1+n2;
e3.setText(String.valueOf(sum));
}
catch(NumberFormatException e)
{

}
}
}
);

The complete source code of MainActivity class is shown below:

207
Android Lab Manual for Novice

MainActivity.java

package com.example.add;
import android.os.Bundle;
import android.widget.*;
import android.app.Activity;
import android.view.Menu;
import android.view.View.*;
import android.view.*;

public class MainActivity extends Activity {


EditText e1,e2,e3;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1=(EditText)findViewById(R.id.editText1);
e2=(EditText)findViewById(R.id.editText2);
e3=(EditText)findViewById(R.id.editText3);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
int n1=Integer.parseInt(e1.getText().toString());
int n2=Integer.parseInt(e2.getText().toString());
int sum=n1+n2;

208
Android Lab Manual for Novice

e3.setText(String.valueOf(sum));
}
catch(NumberFormatException e)
{
}
}
}
);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

The structure of activity_main.xml layout file is shown below:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"

209
Android Lab Manual for Novice

tools:context=".MainActivity" >

<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="87dp"
android:layout_marginTop="55dp"
android:orientation="vertical" >
</LinearLayout>

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:ems="10"
android:gravity="center_vertical|center_horizontal" >

<requestFocus />
</EditText>

<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"

210
Android Lab Manual for Novice

android:layout_below="@+id/linearLayout1"
android:layout_marginTop="34dp"
android:ems="10"
android:gravity="center_vertical|center_horizontal" />

<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2"
android:layout_marginTop="64dp"
android:ems="10"
android:gravity="center_vertical|center_horizontal" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText3"
android:layout_marginTop="54dp"
android:layout_toRightOf="@+id/linearLayout1"
android:text="Add" />

</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

211
Android Lab Manual for Novice

Execution of the Application in Android Studio


On executing the application in Android Studio, the following output is generated:

212
Android Lab Manual for Novice

Enter the two numbers and click on ‘Add’ button. The following output is generated:

Program : Android Program to Compute the Factors of a Given Number


The following program demonstrates using a ScrollView control.
1. Create a new Android application project with the name ‘factors’.
2. Place a plain text control (located in ‘Form Widgets’ tab), a ScrollView control (located
in ‘Composite’ tab) and a button control (located in ‘Form Widgets’ tab) on the layout.
3. Declare the following control variables in MainActivity class.

TextView t;
EditText e;
Button b;
ScrollView s;
String output;

213
Android Lab Manual for Novice

4. Append the following code to onCreate() method of MainActivity class:

t=(TextView)findViewById(R.id.textView1);
e=(EditText)findViewById(R.id.editText1);
b=(Button)findViewById(R.id.button1);
s=(ScrollView)findViewById(R.id.scrollView1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
int n=Integer.parseInt(e.getText().toString());
for (int i=1;i<=n;i++)
{
if ((n % i)==0)
{
output=String.format("%d\n", i);
t.append(output);
}
}
}
catch(NumberFormatException e)
{
}
}
}
);

The complete source code of MainActivity class is shown below:

214
Android Lab Manual for Novice

MainActivity.java

package com.example.factors;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.Menu;
import android.view.View;
import android.view.View.*;
import android.view.*;
import android.widget.Button;
import android.widget.*;

public class MainActivity extends Activity {


TextView t;
EditText e;
Button b;
ScrollView s;
String output;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(TextView)findViewById(R.id.textView1);
e=(EditText)findViewById(R.id.editText1);
b=(Button)findViewById(R.id.button1);
s=(ScrollView)findViewById(R.id.scrollView1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)

215
Android Lab Manual for Novice

{
try
{
int n=Integer.parseInt(e.getText().toString());
for (int i=1;i<=n;i++)
{
if ((n % i)==0)
{
output=String.format("%d\n", i);
t.append(output);
}
}
}
catch(NumberFormatException e)
{
}
}
}
);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

The structure of activity_main.xml layout file is shown below:

216
Android Lab Manual for Novice

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="52dp"
android:ems="10"
android:gravity="center_vertical|center_horizontal" />

<ScrollView
android:id="@+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginTop="64dp"
android:layout_toLeftOf="@+id/button1" >

</ScrollView>

217
Android Lab Manual for Novice

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="34dp"
android:text="Find" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/scrollView1"
android:layout_marginTop="36dp"
android:text="Factors"
android:textSize="20sp" />
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

218
Android Lab Manual for Novice

Execution of the Application in Android Studio


On executing the application in Android Studio, the following output is generated.

Enter a number in a text field and click on ‘Find’ button.

Program : Android Program to Display Current Date in a Text View


Control

The following program demonstrates using a ‘java.util.Calendar’ class.


1. Create a new Android application project with the name ‘datepicker’.
2. Place a TextView control (located in ‘FormWidgets’ tab) on the layout.
3. Declare the following variables in MainActivity class.

219
Android Lab Manual for Novice

Calendar calendar;
int day,month,year;
TextView t;

4. Append the following code to onCreate() method of MainActivity class:

t=(TextView)findViewById(R.id.textView1);

5. Add the following methods to MainActivity class.


public void display(View v)
{
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
displayDate(year, month+1, day);
}

private void displayDate(int year, int month, int day) {


StringBuilder sb=newStringBuilder();
sb.append(day);
sb.append("/");
sb.append(month);
sb.append("/");
sb.append(year);
t.setText(sb);
}

The complete source code of MainActivity class is shown below:

220
Android Lab Manual for Novice

MainActivity.java

package com.example.datepicker;
import java.util.Calendar;

public class MainActivity extends Activity {


Calendar calendar;
int day,month,year;
TextView t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(TextView)findViewById(R.id.textView1);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

public void display(View v)


{
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
displayDate(year, month+1, day);
}

221
Android Lab Manual for Novice

private void displayDate(int year, int month, int day) {


StringBuilder sb=new StringBuilder();
sb.append(day);
sb.append("/");
sb.append(month);
sb.append("/");
sb.append(year);
t.setText(sb);
}
}

The structure of activity_main.xml layout file is shown below:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"

222
Android Lab Manual for Novice

android:layout_centerHorizontal="true"
android:layout_marginTop="53dp"
android:textSize="30sp" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="Display Date"
android:onClick="display"
/>
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

223
Android Lab Manual for Novice

Execution of the Application in Android Studio


On executing the application in Android Studio, the following output is generated.

2.9 Layouts in Android


A layout specifies the arrangement of controls on the container. This section explores the
different layouts supported by Android.

2.9.1 Linear Layout


This layout adds the controls to the layout next to each other, either horizontally or vertically
based on the XML property ‘android:orientation’ set for the control. The valid values for the
property are ‘vertical’ for vertical linear layout and ‘horizontal’ for horizontal linear layout.

224
Android Lab Manual for Novice

Vertical Linear Layout

The following program demonstrates the vertical linear layout.


1. Create a new Android application project with the name ‘linearlayout’.
2. Right-click on the ‘layout’ folder under ‘res’ folder and create a new layout with the root
element <LinearLayout> with the name ‘linear_layout1’ as shown below:
3. Add three text view controls to the layout with the ‘Text’ property set to ‘RED’,
‘GREEN’ and ‘BLUE’, respectively and the background set to ‘#ff0000’,’#00ff00’ and
‘#0000ff’, respectively.

The structure of ‘linear_layout1.xml’ layout file is shown below:

linear_layout1.xml

<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff0000"
android:gravity="center_horizontal"
android:text="RED"
android:textSize="30sp"/>

225
Android Lab Manual for Novice

<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00ff00"
android:gravity="center_horizontal"
android:text="GREEN"
android:textSize="30sp"/>

<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#0000ff"
android:gravity="center_horizontal"
android:text="BLUE"
android:textSize="30sp"/>
</LinearLayout>

In the MainActivity class change the last statement of onCreate() method to the statement shown
below in bold and italic.

The source code of MainActivity class is shown below:

MainActivity.java

package com.example.linearlayout;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

226
Android Lab Manual for Novice

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linear_layout1);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

On deploying the project in the emulator, the following output is generated:

227
Android Lab Manual for Novice

Execution of the Application in Android Studio


Creating a New Layout File in Android
 Expand ‘res’ node and right-click on ‘layout’ node. Select ‘New’ → ‘Layout resource
file’ from the shortcut menu as shown below:

The following dialog is displayed:

 Enter the name of the file as ‘linear_layout1’ as shown above and click on ‘OK’ button.
 Enter the code shown above in ‘linear_layout1.xml’ file.
 Modify MainActivity.java file to use the new layout.

On executing the application in Android Studio, the following output is generated.

228
Android Lab Manual for Novice

Horizontal Linear Layout


The following program demonstrates the horizontal linear layout.

1. In the above application, right-click on the ‘layout’ folder under ‘res’ folder and create a
new layout with the root element <LinearLayout> with the name ‘linear_layout2’ as
shown below:
2. Add five text view controls to the layout with the ‘Text’ property set to ‘RED’,
‘GREEN’, ‘BLUE’, ‘YELLOW’ and ‘MAGENTA’, respectively and the background set
to ‘#ff0000’,’#00ff00’, ‘#0000ff’, ‘#ffff00’ and ‘#00ffff’, respectively.

The structure of ‘linear_layout2.xml’ layout file is shown below:

229
Android Lab Manual for Novice

linear_layout2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#ff0000"
android:gravity="center_vertical"
android:text="RED"
android:textSize="20sp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#00ff00"
android:gravity="center_vertical"
android:text="GREEN"
android:textSize="20sp" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#0000ff"

230
Android Lab Manual for Novice

android:gravity="center_vertical"
android:text="BLUE"
android:textSize="20sp" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#ffff00"
android:gravity="center_vertical"
android:text="YELLOW"
android:textSize="20sp" />

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#ff00ff"
android:gravity="center_vertical"
android:text="MAGENTA"
android:textSize="20sp" />
</LinearLayout>

In the MainActivity class change the statement shown in bold and italic to the one shown below:
setContentView(R.layout.linear_layout2);

On deploying the project in the emulator, the following output is generated:

231
Android Lab Manual for Novice

Execution of the Application in Android Studio


 Create a new layout with the name ‘linear_layout2’ as describe above.
 Enter the code shown above in ‘linear_layout2.xml’ file.
 Modify MainActivity.java file to use the new layout.
On executing the application in Android Studio, the following output is generated.

232
Android Lab Manual for Novice

2.9.2 Table Layout


The following program demonstrates the table layout.

1. In the above application, right-click on the ‘layout’ folder under ‘res’ folder and create a
new layout with the root element <TableLayout> with the name ‘table_layout’ as shown
below:
2. Add six text view controls to the layout with the ‘Text’ property set to ‘RED’, ‘GREEN’,
‘MAGENTA’, ‘BLUE’, ‘YELLOW’ and ‘CYAN’, respectively and the background set to
‘#ff0000’,’#00ff00’, ‘#ff00ff’, ‘#0000ff ‘, ‘#ffff00’ and ‘#00ffff’, respectively.

The structure of ‘table_layout.xml’ layout file is shown below:

table_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TableRow
android:id="@+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff0000"
android:text="RED"

233
Android Lab Manual for Novice

android:textSize="30sp" />

<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00ff00"
android:text="GREEN"
android:textSize="30sp" />

<TextView
android:id="@+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff00ff"
android:text="Magenta"
android:textSize="30sp" />

</TableRow>

<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0000ff"
android:text="BLUE"

234
Android Lab Manual for Novice

android:textSize="30sp" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffff00"
android:text="YELLOW"
android:textSize="30sp" />

<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00ffff"
android:text="Cyan"
android:textSize="30sp" />

</TableRow>
</TableLayout>

In the MainActivity class change the statement shown in bold and italic to the one shown below:

setContentView(R.layout.table_layout);

On deploying the project in the emulator, the following output is generated:

235
Android Lab Manual for Novice

Execution of the Application in Android Studio


 Create a new layout with the name ‘table_layout’ as describe above.
 Enter the code shown above in ‘table_layout.xml’ file.
 Modify MainActivity.java file to use the new layout.
On executing the application in Android Studio, the following output is generated.

236
Android Lab Manual for Novice

Another example of table layout is shown below:

<?xml version="1.0" encoding="utf-8"?>


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TableRow
android:id="@+id/tableRow1"
android:layout_width="100px"
android:layout_height="wrap_content" >

<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="One" />

<TextView
android:id="@+id/textView2"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="Two" />

</TableRow>

<TableRow
android:id="@+id/tableRow2"
android:layout_width="100px"
android:layout_height="wrap_content" >

237
Android Lab Manual for Novice

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Four" />

</TableRow>
</TableLayout>

On deploying the project in the emulator, the following output is generated:

238
Android Lab Manual for Novice

2.9.3 Absolute Layout


This layout organizes the controls on the layout at the specified x and y co-ordinates. This is the
most flexible layout in which the controls can be dragged and dropped at the required position.

The following program demonstrates the absolute layout.


1. In the above application, right-click on the ‘layout’ folder under ‘res’ folder and create a
new layout with the root element <AbsoluteLayout> with the name ‘absolute_layout’ as
shown below:
2. Add two text view and edit controls on the layout as shown below:

The structure of ‘absolute_layout.xml’ layout file is shown below:


absolute_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="52dp"
android:layout_y="106dp"
android:text="Password :" />

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

239
Android Lab Manual for Novice

android:layout_x="147dp"
android:layout_y="33dp"
android:ems="10" >

<requestFocus />
</EditText>

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="50dp"
android:layout_y="43dp"
android:text="User Name :" />

<EditText
android:id="@+id/editText2"
android:layout_width="155dp"
android:layout_height="wrap_content"
android:layout_x="146dp"
android:layout_y="97dp"
android:ems="10"
android:inputType="textPassword" />
</AbsoluteLayout>

In the MainActivity class change the statement shown in bold and italic to the one shown below:
setContentView(R.layout.absolute_layout);

On deploying the project in the emulator, the following output is generated:

240
Android Lab Manual for Novice

Execution of the Application in Android Studio


 Create a new layout with the name ‘absolute_layout’ as describe above.
 Enter the code shown above in ‘absolute_layout.xml’ file.
 Modify MainActivity.java file to use the new layout.
On executing the application in Android Studio, the following output is generated.

241
Android Lab Manual for Novice

2.9.4 Relative Layout


RelativeLayout is a view group which displays the child views in the relative positions. The
position of each view is specified relative to the element added earlier or relative to the parent
element. This is the default layout used by both ‘eclipse’ and ‘AndroidStudio’. When a particular
control is selected in the outline view, it’s position relative to the other controls in the view is
graphically depicted as shown in the following figure:

Some important layout properties available to views in RelativeLayout are depicted in the
following table:
Layout Attribute Description
layout_above Places the view above the specified view id
layout_below Places the view below the specified view id
layout_toLeftOf Places the view left of the specified view id
layout_toRightOf Places the view right of the specified view id
layout_centerHorizontal If true, the view will be horizontally center
aligned within its parent.
layout_centerVertical If true, the view will be vertically center
aligned within its parent.

242
Android Lab Manual for Novice

The following layout demonstrates the following properties of RelativeLayout:


 android:layout_alignParentTop
 android:layout_alignParentBottom
 android:layout_alignParentLeft
 android:layout_alignParentRight and
 android:layout_centerHorizontal

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Button1" />

<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Button2" />

<Button
android:id="@+id/btn3"

243
Android Lab Manual for Novice

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button3" />

<Button
android:id="@+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Button4" />

<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button5" />

<Button
android:id="@+id/btn6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Button6" />
</RelativeLayout>

The layout generated from the above layout file is shown below:

244
Android Lab Manual for Novice

Execution in Android Studio


On deploying the project in Android Studio, the following output is generated:

245
Android Lab Manual for Novice

The following layout demonstrates using ‘android:layout_width’ property of RelativeLayout


which is set a value as shown below:

android:layout_width="match_parent"

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button2" />
</RelativeLayout>

The layout generated from the above layout file is shown below:

246
Android Lab Manual for Novice

Execution in Android Studio


On deploying the project in Android Studio, the following output is generated:

247
Android Lab Manual for Novice

The following layout demonstrates using the ‘android:layout_centerVertical’ property of


RelativeLayout.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Button2" />

<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button3" />
</RelativeLayout>

248
Android Lab Manual for Novice

The layout generated from the above layout file is shown below:

Execution in Android Studio


On deploying the project in Android Studio, the following output is generated:

249
Android Lab Manual for Novice

The following layout demonstrates the following properties of RelativeLayout.


 android:layout_toEndOf
 android:layout_toRightOf

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btn1"
android:layout_centerHorizontal="true"
android:text="Button2" />

<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/btn2"
android:layout_alignBottom="@+id/btn2"

250
Android Lab Manual for Novice

android:text="Button3" />
<Button
android:id="@+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btn3"
android:text="Button4" />
<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@+id/btn1"
android:layout_toRightOf="@+id/btn1"
android:layout_alignParentRight="true"
android:text="Button5" />
</RelativeLayout>

The layout generated from the above layout file is shown below:

251
Android Lab Manual for Novice

Execution in Android Studio


On deploying the project in Android Studio, the following output is generated:

The following layout demonstrates the following properties of RelativeLayout.

 android:layout_centerVertical
 android:layout_centerHorizontal
 android:layout_alignTop
 android:layout_alignBottom
 android:layout_alignLeft
 android:layout_alignRight

252
Android Lab Manual for Novice

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:text="Button1" />

<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/btn1"
android:text="Button2" />

<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btn1"
android:text="Button3" />

<Button

253
Android Lab Manual for Novice

android:id="@+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/btn1"
android:text="Button4" />

<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/btn1"
android:text="Button5" />
</RelativeLayout>

The layout generated from the above layout file is shown below:

254
Android Lab Manual for Novice

Execution in Android Studio


On deploying the project in Android Studio, the following output is generated:

2.9.5 Grid Layout


This layout is supported only in API level 14 and higher. It organizes the elements in a
rectangular grid having specified no. of columns and rows. The GridLayout has the property
‘android:rowCount’ for specifying the no. of rows and ‘android:columnCount’ for specifying
the no. of columns.

The following layout organizes the nine buttons with ‘Text’ property set to 1..9 in a rectangular
grid of 3 rows and 3 columns.

255
Android Lab Manual for Novice

activity_main.xml

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/GridLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnCount="3"
android:rowCount="3"
android:orientation="horizontal"
tools:context=".GridXMLActivity" >
<Button
android:id="@+id/button1"
android:layout_gravity="left|top"
android:text="1" />

<Button
android:id="@+id/button2"
android:layout_gravity="left|top"
android:text="2" />

<Button
android:id="@+id/button3"
android:layout_gravity="left|top"
android:text="3" />

<Button
android:id="@+id/button4"
android:layout_gravity="left|top"
android:text="4" />

256
Android Lab Manual for Novice

<Button
android:id="@+id/button5"
android:layout_gravity="left|top"
android:text="5" />

<Button
android:id="@+id/button6"
android:layout_gravity="left|top"
android:text="6" />

<Button
android:id="@+id/button7"
android:layout_gravity="left|top"
android:text="7" />

<Button
android:id="@+id/button8"
android:layout_gravity="left|top"
android:text="8" />

<Button
android:id="@+id/button9"
android:layout_gravity="left|top"
android:text="9" />
</GridLayout>

The layout generated from the above layout file is shown below:

257
Android Lab Manual for Novice

Execution in Android Studio


On deploying the project in Android Studio, the following output is generated:

258
Android Lab Manual for Novice

Placing a Child View in a Specified Cell of a GridLayout


The child view can be placed in a specified cell of a GridLayout by specifying the intersecting
row and column using the properties, ‘android:layout_row’ and ‘android:layout_column’ as
demonstrated in the following example.

The following layout creates a GridLayout of 5 rows and 5 columns and places three buttons
with the ‘Text’ property set to ‘Button1’, ‘Button2’ and ‘Button3’, respectively in the first
column of three rows

activity_main.xml

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/GridLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnCount="5"
android:rowCount="5"
android:orientation="horizontal"
tools:context=".GridXMLActivity" >

<Button
android:id="@+id/btn1"
android:layout_column="1"
android:layout_row="1"
android:layout_gravity="left|top"
android:text="Button1" />

<Button
android:id="@+id/btn2"

259
Android Lab Manual for Novice

android:layout_column="1"
android:layout_row="2"
android:layout_gravity="left|top"
android:text="Button2" />

<Button
android:id="@+id/btn3"
android:layout_column="1"
android:layout_row="3"
android:layout_gravity="left|top"
android:text="Button3" />
</GridLayout>

The layout generated from the above layout file is shown below:

Execution in Android Studio


On deploying the project in Android Studio, the following output is generated:

260
Android Lab Manual for Novice

android:layout_columnSpan and android:layout_rowSpan Properties

android:layout_columnSpan and android:layout_rowSpan properties are employed for placing a


control in a GridLayout spanning multiple rows and columns, respectively. In the following
layout the TextView control with the caption ‘Row 2,3 column 1,2,3’ spans two rows and four
columns.

activity_main.xml

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/GridLayout1"
android:layout_width="wrap_content"

261
Android Lab Manual for Novice

android:layout_height="wrap_content"
android:columnCount="4"
android:orientation="horizontal"
android:rowCount="4"
tools:context=".GridXMLActivity" >

<TextView
android:id="@+id/textView1"
android:layout_column="1"
android:layout_gravity="left|top"
android:layout_row="1"
android:background="#ff0000"
android:text="Row 1 column 1" />

<TextView
android:id="@+id/textView2"
android:layout_column="2"
android:layout_gravity="left|top"
android:layout_row="1"
android:background="#00ff00"
android:text="Row 1 column 2" />

<TextView
android:id="@+id/textView3"
android:layout_column="3"
android:layout_gravity="left|top"
android:layout_row="1"
android:background="#0000ff"
android:text="Row 1 column 3" />

<TextView

262
Android Lab Manual for Novice

android:id="@+id/textView4"
android:layout_gravity="fill"
android:layout_columnSpan="4"
android:layout_rowSpan="2"
android:background="#00ffff"
android:text="Row 2,3 column 1,2,3" />
</GridLayout>

The layout generated from the above layout file is shown below:

Execution in Android Studio


On deploying the project in Android Studio, the following output is generated:

263
Android Lab Manual for Novice

2.9.6 Frame Layout


It represents a simple layout for Android application which displays a single view at a specific
area of a layout. It is used for displaying overlapping child views.

The following layout file employs FrameLayout for placing two overlapping child views, image
view and a text view.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/framelayout" >
<ImageView
android:id="@+id/frameImage"

264
Android Lab Manual for Novice

android:layout_width="200dp"
android:layout_height="300dp"
android:src="@drawable/ic_launcher"
android:layout_gravity="center"
android:clickable="true" />
<TextView
android:id="@+id/frameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Frame Layout"
android:textSize="15sp"
android:textStyle="bold"
android:visibility="visible"
android:layout_gravity="center" />

</FrameLayout>

On deploying the application on target device, the following output is generated:

265
Android Lab Manual for Novice

Change the statement shown in bold and italic with the following statement:
android:visibility="gone"
which hides the child view, TextView.

On re-deploying the application on target device, the following output is generated:

In the above example, the frame layout contains two overlapping views:
 ImageView and
 TextView

Execution in Android Studio

 Create a new project in Android Studio


 Copy ic_launcher.png file to res/drawable folder under project folder.
 Copy the code shown above in ‘activity_main.xml’ file.

On deploying the project in Android Studio, the following output is generated:

266
Android Lab Manual for Novice

Change the statement shown in bold and italic with the following statement:
android:visibility="gone"
which hides the child view, TextView.
On re-deploying the application on target device, the following output is generated:

267
Android Lab Manual for Novice

layout_gravity Attribute
It is the property of FrameLayout which enables controlling the position of child element.

Adding Child Views to FrameLayout at Runtime


The child views can be added to FrameLayout dynamically at runtime using addView() method
of FrameLayout class as demonstrated in the following example. The addView() method accepts
a single parameter, the reference to the control to be added to a Frame Layout.

MainActivity.java

package com.example.framelayout;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {


TextView t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FrameLayout frame = (FrameLayout) findViewById(R.id.framelayout);

268
Android Lab Manual for Novice

ImageView image = (ImageView) findViewById(R.id.frameImage);


// add a new element to the FrameLayout
t = new TextView(this);
t.setText("SIBER");
t.setTextColor(Color.RED);
t.setTextSize(30);
t.setGravity(Gravity.CENTER);
frame.addView(t);
image.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View arg0) {
if (t.getVisibility() == View.GONE)
t.setVisibility(View.VISIBLE);
else
t.setVisibility(View.GONE);
}

On deploying the application on target device, the following output is generated:

269
Android Lab Manual for Novice

Click on ImageView, the following output is generated:

270
Android Lab Manual for Novice

Execution in Android Studio


On deploying the project in Android Studio, the following output is generated:

Click on ImageView, the following output is generated:

271
Android Lab Manual for Novice

MainActivity.java

package com.example.framelayout;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {


TextView t1,t2,t3;
int code;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FrameLayout frame = (FrameLayout) findViewById(R.id.framelayout);
Button b = (Button) findViewById(R.id.button1);
code=1;
// add a new element to the FrameLayout
t1 = new TextView(this);
t1.setText("SIBER");
t1.setTextColor(Color.RED);
t1.setTextSize(30);

272
Android Lab Manual for Novice

t1.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL);
frame.addView(t1);

t2 = new TextView(this);
t2.setText("SIBER");
t2.setTextColor(Color.GREEN);
t2.setTextSize(30);
t2.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL);
frame.addView(t2);

t3 = new TextView(this);
t3.setText("SIBER");
t3.setTextColor(Color.BLUE);
t3.setTextSize(30);
t3.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL);
frame.addView(t3);
b.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public void onClick(View arg0) {

switch(code)
{

273
Android Lab Manual for Novice

case 1:
t1.setVisibility(View.VISIBLE);
t2.setVisibility(View.GONE);
t3.setVisibility(View.GONE);
break;
case 2:
t2.setVisibility(View.VISIBLE);
t1.setVisibility(View.GONE);
t3.setVisibility(View.GONE);
break;
case 3:
t3.setVisibility(View.VISIBLE);
t1.setVisibility(View.GONE);
t2.setVisibility(View.GONE);
break;
}
code++;
if (code == 3)
code=1;
}
}

The structure of ‘activity_main.xml’ file is shown below:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/framelayout" >

274
Android Lab Manual for Novice

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Next"
android:onClick=”next” />
</FrameLayout>

On deploying the application on target device, the following output is generated:

Click on ‘Next’ button, the following output is generated:

275
Android Lab Manual for Novice

Again clicking ‘Next’ generates the following output:

Execution in Android Studio


On deploying the project in Android Studio, the following output is generated:

276
Android Lab Manual for Novice

Click on ‘Next’ button, the following output is generated:

277
Android Lab Manual for Novice

Again clicking ‘Next’ generates the following output:

Program: Android Program to Display Image and Text on the Button


Control
The button control supports an XML property with the name, ‘android:drawableLeft’ which can
be set to display image on a button control. The different steps involved in displaying an image
on the button control are enumerated below:
1. Create a new Android application project with the name ‘buttontext’.
2. Drag and drop a button control from the ‘Form Widgets’ tab on the layout.
3. In the property sheet of a button control, locate the property with the name
‘drawableLeft’ as shown in the following figure:

278
Android Lab Manual for Novice

4. Click on the three ellipsis next to the property. The following dialog is displayed.

5. Expand ‘Drawable’ node and select the image ‘ic_launcher’. Click on ‘OK’ button.
6. Change the ‘Text’ property of the button control to ‘Android’.

The structure of ‘activity_main.xml’ layout file is shown below:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"

279
Android Lab Manual for Novice

android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android"
android:drawableLeft="@drawable/ic_launcher"
android:drawablePadding="10dp"/>
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

280
Android Lab Manual for Novice

Execution of the Application in Android Studio


 Create a new project with the name ‘ButtonImge’.
 Double-click on activity_main.xml file to open it in the editor.
 Select the button control in ‘Design’ view
 Click on the three ellipsis next to ‘drawableLeft’ property and select the ic_launcher
image from ‘drawable’ folder as shown in the following figure:

 Set the ‘Text’ property of the button control to ‘Android’.


 Deploy the application on target device.

The following output is generated:

281
Android Lab Manual for Novice

Program: Android Program to Display Multiple Lines in a TextView


Control
The following program demonstrates displaying multiple lines in a TextView control
1. Create a new Android application project with the name ‘lines’.
2. Place a TextView control (located in ‘FormWidgets’ tab) on the layout.
3. Declare the following variable in MainActivity class.

String output;

4. Append the following lines to onCreate() method of MainActivity class.

TextView t=(TextView)findViewById(R.id.textView1);
for(int i=1;i<=50;i++)

282
Android Lab Manual for Novice

{
output=String.format("Line %d\n",i);
t.append(output);
}

The complete source code of MainActivity class is shown below:

MainActivity.java

package com.example.lines;
import android.os.Bundle;
import android.widget.*;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {


String output;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView t=(TextView)findViewById(R.id.textView1);
for(int i=1;i<=50;i++)
{
output=String.format("Line %d\n",i);
t.append(output);
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

283
Android Lab Manual for Novice

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

The structure of ‘activity_main.xml’ layout file is shown below:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="76dp" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"

284
Android Lab Manual for Novice

android:layout_height="wrap_content"
android:layout_alignLeft="@+id/scrollView1"
android:layout_alignTop="@+id/scrollView1"
android:layout_marginLeft="36dp"
android:text="" />
</ScrollView>
</LinearLayout>
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

Execution of the Application in Android Studio


 Create a new project with the name ‘lines’.
 Place a TextView control (located in ‘FormWidgets’ tab) on the layout.
 Copy the code shown above in MainActivity class.
 Deploy the project on target device.

285
Android Lab Manual for Novice

The following output is generated:

To scroll through the data, click on the control and hold down left mouse button and drag the
mouse.

Program: Android Program to Hide Title Bar of MainActivity

‘android.view’ package contains a class with the name ‘WindowManager.LayoutParams’ which


contains the XML attributes for changing the window behavior [10]. The hierarchy of
‘WindowManager.LayoutParams’ class is shown below:

286
Android Lab Manual for Novice

The following program demonstrates hiding title bar of a MainActivity window.


1. Create a new Android application project with the name ‘hidetitlebar’.
2. Insert the following code in onCreate() method of MainActivity class before call to
setContentView() method.

requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

The complete source code of MainActivity class is shown below:


MainActivity.java

package com.example.hidetitlebar;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {

287
Android Lab Manual for Novice

super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

On deploying the project in the emulator, the following output is generated:

288
Android Lab Manual for Novice

Execution of the Application in Android Studio


 Create a new project with the name ‘hidetitlebar’.
 Copy the above code in MainActivity class.
 Deploy the project on a target device.

The following output is generated:

Program: Android Program to Change Launcher Activity


AndroidManifest.xml file contains the configuration of launcher activity which is by default,
MainActivity. This program demonstrates changing the launcher activity to a different activity
of an application.
1. Create a new Android application project with the name ‘launcher’.

The source code of MainActivity class is shown below:

289
Android Lab Manual for Novice

MainActivity.java

package com.example.launcher;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

The structure of ‘activity_main.xml’ layout file is shown below:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"

290
Android Lab Manual for Novice

android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>

2. To create another activity, expand ‘src’ node in the package explorer, right-click on the
package ‘com.example.launcher’ and select New → Class from the shortcut menu as
shown in the following figure:

Enter the name of the class as ‘SecondActivity’ and click on ‘Finish’ button.

291
Android Lab Manual for Novice

The class with the name ‘SecondActivity’ is generated in the package com.example.launcher.

3. Insert the following code in ‘SecondActivity’ class.

SecondActivity.java

package com.example.launcher;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class SecondActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {

292
Android Lab Manual for Novice

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

4. Creating a layout for SecondActivity.

To create a layout for the SecondActivity, right-click on ‘layout’ folder under ‘res’ folder and
select New → Android XML File from the shortcut menu as shown below:

293
Android Lab Manual for Novice

Enter the name of the file as ‘activity_second’ and click on ‘Finish’ button.

5. Place an ‘ImageView’ control and ‘TextView’ control with the text ‘Second Activity’ as
shown in the following figure:

294
Android Lab Manual for Novice

The structure of ‘activity_second.xml’ layout file is shown below:

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="125dp"
android:text="Second Activity"
android:textColor="#0000ff"
android:textSize="25sp" />

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="22dp"
android:layout_toLeftOf="@+id/textView1"
android:src="@drawable/ic_launcher" />
</RelativeLayout>

295
Android Lab Manual for Novice

6. Registering ‘SecondActivity’ in AndroidManifest.xml file as a launcher activity.


To render the ‘SecondActivity’ as launcher activity, add <intent-filter> child element
inside <activity> element containing ‘android:name’ attribute of <category> element set
to ‘android.intent.category.LAUNCHER’ as shown in the following code:

<activity
android:name="com.example.launcher.SecondActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="MainActivity"></activity>

The final structure of AndroidManifest.xml file is shown below:


AndroidManifest.xml

296
Android Lab Manual for Novice

On deploying the project in the emulator, the following output is generated:

Program: Android Program to Change Screen Orientation


1. Create a new Android application project with the name ‘screenorientation’.
2. Append the following line to onCreate() method of MainActivity class.

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_
LANDSCAPE);

The complete source code of MainActivity class is shown below:

MainActivity.java

package com.example.screenorientation;
import android.os.Bundle;
import android.app.Activity;

297
Android Lab Manual for Novice

import android.content.pm.ActivityInfo;
import android.view.Menu;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_
LANDSCAPE);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

The structure of ‘activity_main.xml’ layout file is shown below:


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"

298
Android Lab Manual for Novice

tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textSize="30sp" />
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

Execution of the Application in Android Studio


 Create a new project with the name ‘ScreenOrientation’.
 Copy the above code in MainActivity class.
 Deploy the project on a target device.

299
Android Lab Manual for Novice

The following output is generated:

Program: Android Program to Draw Simple Graphics


1. Create a new Android application project with the name ‘simplegraphics’.
The source code of MainActivity class is shown below:
MainActivity.java

package com.example.simplegraphics;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;

300
Android Lab Manual for Novice

import android.graphics.Paint;
import android.view.View;

public class MainActivity extends Activity {

DemoView demoview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
demoview = new DemoView(this);
setContentView(demoview);
}

private class DemoView extends View{


public DemoView(Context context){
super(context);
}

@Override protected void onDraw(Canvas canvas) {


super.onDraw(canvas);

// custom drawing code here


Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);

// make the entire canvas white


paint.setColor(Color.WHITE);
canvas.drawPaint(paint);

// draw blue circle with anti aliasing turned off

301
Android Lab Manual for Novice

paint.setAntiAlias(false);
paint.setColor(Color.BLUE);
canvas.drawCircle(20, 20, 15, paint);

// draw green circle with anti aliasing turned on


paint.setAntiAlias(true);
paint.setColor(Color.GREEN);
canvas.drawCircle(60, 20, 15, paint);

// draw red rectangle with anti aliasing turned off


paint.setAntiAlias(false);
paint.setColor(Color.RED);
canvas.drawRect(100, 5, 200, 30, paint);

// draw the rotated text


canvas.rotate(-45);

paint.setStyle(Paint.Style.FILL);
canvas.drawText("Graphics Rotation", 40, 180, paint);

//undo the rotate


canvas.restore();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

302
Android Lab Manual for Novice

The structure of ‘activity_main.xml’ layout file is shown below:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="32dp"
android:layout_marginTop="34dp"
android:text="Shake to change color" />
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

303
Android Lab Manual for Novice

Execution of the Application in Android Studio


 Create a new project with the name ‘SimpleGraphics’.
 Copy the above code in MainActivity class.
 Deploy the project on a target device.

The same output as above is generated:

Program: Android Program for Creating a Custom Toast


1. Create a new Android application project with the name ‘custom_toast’.
2. Expand ‘res’ folder.
3. Right-click on ‘layout’ folder and select ‘New’ → ‘Android XML File’ from the shortcut
menu as shown below:

304
Android Lab Manual for Novice

4. Enter the file name as ‘mylayout’ and accept other defaults. Click on ‘Finish’ button.

5. Place an ImageView (located in ‘Images and Media’ tab) and a TextView

305
Android Lab Manual for Novice

The structure of ‘mylayout.xml’ layout file is shown below:

mylayout.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/mylayout">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"

306
Android Lab Manual for Novice

android:layout_height="wrap_content"
android:text="Welcome To Android" />

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
</LinearLayout>

The complete source code of MainActivity class is shown below:

MainActivity.java

package com.example.custom_toast;
import android.os.Bundle;

307
Android Lab Manual for Novice

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater li=getLayoutInflater();
View layout=li.inflate(R.layout.mylayout, (ViewGroup)findViewById(R.id.mylayout));
Toast t=new Toast(this);
t.setDuration(Toast.LENGTH_LONG);
t.setView(layout);
t.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

On deploying the project in the emulator, the following output is generated:

308
Android Lab Manual for Novice

Execution of the Application in Android Studio


 Create a new project with the name ‘CustomToast’.
 Copy ‘ic_launcher.png’ file to ‘res/drawable’ folder.
 Create a new XML layout file ‘mylayout’ as describe above.
 Copy the above code in MainActivity class.
 Deploy the project on a target device.
The following output is generated:

309
Android Lab Manual for Novice

Displaying Custom Message in a Custom Toast


The following program demonstrates changing the default message of a custom toast created
above.

Change the source code of MainActivity class is shown below:

MainActivity.java

package com.example.custom_toast;

import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {


TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater li=getLayoutInflater();
View layout=li.inflate(R.layout.mylayout, (ViewGroup)findViewById(R.id.mylayout));
tv=(TextView) layout.findViewById(R.id.textView1);
tv.setText("Welcome to SIBER");
Toast t=new Toast(this);

310
Android Lab Manual for Novice

t.setDuration(Toast.LENGTH_LONG);
t.setView(layout);
t.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

Adding TypeCasting in Editor

311
Android Lab Manual for Novice

On deploying the project in the emulator, the following output is generated:

Execution of the Application in Android Studio


 Modify the MainActivity class as shown above.
 Deploy the project on a target device.
The following output is generated:

312
Android Lab Manual for Novice

Using Timer Class in Android


1. Create a new Android application project with the name ‘timer1’.
2. Change the MainActivity class declaration as shown below:
public class MainActivity extends Activity implements OnClickListener

3. Place a button control, an edit control, and two text view controls on the layout.
4. Change the ‘Text’ property of button control to ‘Start’.
5. Declare the following variables in MainActivity class

private MyTimer timer;


private Boolean timer_flag=false;
private long startTime = 10000;
private final long interval = 1000;
private Button start;
private TextView text,time_eplapsed;
private EditText e;
private long timeElapsed;

6. Append the following code to onCreate() method of MainActivity class.

start = (Button) findViewById(R.id.startbutton);


start.setOnClickListener(this);
text = (TextView) findViewById(R.id.timer);
e=(EditText) findViewById(R.id.editText1);
time_eplapsed = (TextView) findViewById(R.id.timeElapsed);

7. Add onClick() event handler to MainActivity class as shown below:

public void onClick(View v) {


// TODO Auto-generated method stub

313
Android Lab Manual for Novice

if (!e.getText().toString().equals(""))
startTime=Integer.parseInt(e.getText().toString())*1000;
text.setText(text.getText() + String.valueOf(startTime/1000));
timer = new MyTimer(startTime, interval);

if (!timer_flag) {
timer.start();
timer_flag = true;
start.setText("Start");
} else {
timer.cancel();
timer_flag = false;
start.setText("Reset");
}

8. Add a nested private helper class to MainActivity class as shown below:

private class MyTimer extends CountDownTimer {


public MyTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}

@Override
public void onFinish() {
// TODO Auto-generated method stub
text.setText("Time's up!");
time_eplapsed.setText("Time Elapsed: " + String.valueOf(startTime/1000));
}

@Override

314
Android Lab Manual for Novice

public void onTick(long millisUntilFinished) {


// TODO Auto-generated method stub
text.setText("Time remain:" + ((millisUntilFinished/1000)+1));
timeElapsed = (startTime - millisUntilFinished)/1000;
time_eplapsed.setText("Time Elapsed: "
+ String.valueOf(timeElapsed));
}
}

The structure of MainActivity class is shown below:

MainActivity.java

package com.example.timer1;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

private MyTimer timer;


private Boolean timer_flag=false;
private long startTime = 10000;
private final long interval = 1000;

315
Android Lab Manual for Novice

private Button start;


private TextView text,time_eplapsed;
private EditText e;
private long timeElapsed;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.startbutton);
start.setOnClickListener(this);
text = (TextView) findViewById(R.id.timer);
e=(EditText) findViewById(R.id.editText1);
time_eplapsed = (TextView) findViewById(R.id.timeElapsed);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!e.getText().toString().equals(""))
startTime=Integer.parseInt(e.getText().toString())*1000;
text.setText(text.getText() + String.valueOf(startTime/1000));
timer = new MyTimer(startTime, interval);

if (!timer_flag) {
timer.start();
timer_flag = true;
start.setText("Start");
} else {
timer.cancel();
timer_flag = false;

316
Android Lab Manual for Novice

start.setText("Reset");
}
}

private class MyTimer extends CountDownTimer {


public MyTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}

@Override
public void onFinish() {
// TODO Auto-generated method stub
text.setText("Time's up!");
time_eplapsed.setText("Time Elapsed: " + String.valueOf(startTime/1000));
}

@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
text.setText("Time remain:" + ((millisUntilFinished/1000)+1));
timeElapsed = (startTime - millisUntilFinished)/1000;
time_eplapsed.setText("Time Elapsed: "
+ String.valueOf(timeElapsed));
}
}
}

The structure of ‘activity_main.xml’ file is shown below:

317
Android Lab Manual for Novice

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
android:id="@+id/startbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start"
android:textAlignment="center">
</Button>

<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp" >
<TableRow>
<TextView
android:id="@+id/timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="Time: "
android:textSize="20dp" />
</TableRow>
</TableLayout>

318
Android Lab Manual for Novice

<TextView
android:id="@+id/timeElapsed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Time elapsed: "
android:textSize="20dp" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter Time" >
<requestFocus />
</EditText>
</LinearLayout>

On deploying the project on a target device, the following output is produced:

319
Android Lab Manual for Novice

2.10 Importing External Projects into Eclipse Workspace


In the current example, the Android project available in the project folder ‘hyperlink’ will be
imported in the current workspace.

For achieving this, follow the steps enumerated below:


 Copy the project folder to the current workspace, ‘F:\pgn’
 Select File → Import from main menu as shown in the following figure:

Expand ‘General’ node and select the option ‘Existing Projects into Workspace’ as shown
below:

320
Android Lab Manual for Novice

Click on ‘Next’ button. The following dialog is displayed:

321
Android Lab Manual for Novice

Click on ‘Browse…’ button next to ‘Select root directory’ option

Click on ‘Finish’ button.

322
Android Lab Manual for Novice

Resolving Import Error


The most common error that occurs while importing projects created in some other editor is

Unable to resolve target 'android-xx'

as shown in the following figure:

This error can be handled by right-clicking on the project in package explorer and selecting
‘Properties’ from shortcut menu as shown in the following figure:

The following dialog is displayed:

323
Android Lab Manual for Novice

Place a check mark in a specified Target Name and click on ‘OK’ button. The error disappears.

324
Android Lab Manual for Novice

CHAPTER 3
Exploring Resources in Android
All the resources of an application are stored in ‘res’ folder under project folder as shown in the
following figure:

The contents of ‘res’ folder are already discussed at depth in previous chapters.

When the Android project is created, by default the following resources are created:
 activity_main.xml layout resource file for MainActivity and
 main.xml menu resource file for main menu

The new resources can be created as required by right-clicking on the appropriate folder and
selecting New → Android XML file from the shortcut menu.

325
Android Lab Manual for Novice

3.1 Creating and Using a String Resource in Android


3.1.1 Creating String Resource in Eclipse
String resources are located in ‘strings.xml’ file in ‘values’ sub-folder of ‘res’ folder as shown in
the above figure.
For creating a new string resource, double-click on ‘strings.xml’ file in package explorer.
The following screen is displayed which contains two tabs:
 Resources
 strings.xml

‘Resources’ tab enables creating string resource visually in the editor. The auto-generated code
can be viewed in ‘strings.xml’ file. The list of already available string resources are displayed
under ‘Resource Elements’.

To create a new string resource, click on ‘Add’ button.


From the dialog that appears, select ‘String’ and click on ‘OK’ button.

326
Android Lab Manual for Novice

Enter the name and value of a string resource and click on the resource under ‘Resource
Elements’ section as shown in the following figure.

The string resource with the name ‘course’ and value ‘MCA’ is created.

327
Android Lab Manual for Novice

Accessing a String Resource


The syntax for accessing a string resource in java code is
R.string.<name>

The syntax for accessing a string resource in XML file is


@string/<name>

where, <name> is the name of the string resource.

Program : Android Program to Illustrate Accessing a String Resource in


Java Code
1. Create a new Android application project with the name ‘message’.
2. Create a new string resource with the name ‘message’ and the value ‘Hello Android’ as
shown below:

The string resource with the name ‘message’ is added to ‘strings.xml’ file as shown below:

328
Android Lab Manual for Novice

strings.xml

<?xmlversion="1.0"encoding="utf-8"?>
<resources>
<string name="app_name">message</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="message">Hello Android</string>
</resources>

In order to access the string in a Java code use the syntax given below:
R.string.message

3. Add a button control to the layout and change its ‘Text’ property to ‘Display Message’.
4. Add the following attribute to <button> element in activity_main.xml file.
android:onClick="displayMessage"
5. Declare the following control variable in MainActivity class.

TextView t;

6. Append the following line to onCreate() method of MainActivity class.

t=(TextView)findViewById(R.id.textView1);

7. Add the following method to MainActivity class.

public void displayMessage(View v)


{
t.setText(R.string.message);
}

329
Android Lab Manual for Novice

The complete source code of MainActivity class is given below:


MainActivity.java

package com.example.message;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {


TextView t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(TextView)findViewById(R.id.textView1);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

public void displayMessage(View v)


{
t.setText(R.string.message);
}
}

330
Android Lab Manual for Novice

The structure of ‘activity_main.xml’ layout file is shown below:


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textSize="20sp" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="102dp"
android:text="Display"
android:onClick="display"/>
</RelativeLayout>

331
Android Lab Manual for Novice

On deploying the project in the emulator, the following output is generated:

3.1.2 Creating a String Resource in Android Studio


String resources are located in ‘strings.xml’ file in ‘values’ sub-folder of ‘res’ folder as shown in
the following figure:

332
Android Lab Manual for Novice

Double-click on the file to open it in a text editor. The root node is ‘resources’ which contains
one or more ‘string’ child nodes with attribute name and value is its content as shown in the
following figure:

To create a new string resource, select ‘Open editor’ link that appears in the right corner of a
window and click on ‘+’ button to add new key. Specify the key and default value as shown in
the following figure and click on ‘OK’ button.

The string resource with the key ‘message’ is created as shown in the following figure:

‘strings.xml’ file contains a new entry as shown in the following figure:

333
Android Lab Manual for Novice

On execution of the application, the following output is generated:

Click on ‘Display Message’ button, the following output is generated:

334
Android Lab Manual for Novice

3.2 Creating and Using a Style Resource in Android


Style resources are located in ‘styles.xml’ file in ‘values’ sub-folder of ‘res’ folder.

Program : Android Program to Illustrate Using Custom Styles in


Android
1. Create a new Android application project with the name ‘style’.
2. Open ‘styles.xml’ file located in ‘values’ folder under ‘res’ folder in a text editor.

Add a new style with the name ‘customstyle’ as shown below:

<resources>
<!--

335
Android Lab Manual for Novice

Base application theme, dependent on API level. This theme is replaced


by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<stylename="AppBaseTheme"parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>

<!-- Application theme. -->


<stylename="AppTheme"parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

<style name="CustomStyle">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>
<item name="android:typeface">serif</item>
<item name="android:textSize">12pt</item>
<item name="android:textColor">#0000FF</item>
</style>
</resources>

3. Place a textview control on the layout


In the Properties window, click on ellipses next to ‘Style’ property and select the custom style
created above as shown below:

336
Android Lab Manual for Novice

On deploying the project in the emulator, the following output is generated:

Execution of the Application in Android Studio


Create a new project in Android Studio.

337
Android Lab Manual for Novice

Click on three ellipsis next to ‘style’ property.

Click on ‘Add new resource’ drop-down list.

Enter the resource name as ‘CustomStyle’ and click on ‘OK’ button.

338
Android Lab Manual for Novice

Add the following code for ‘CustomStyle’.

339
Android Lab Manual for Novice

The style is applied as shown below:

340
Android Lab Manual for Novice

In the ‘Properties’ table the ‘style’ property is set as shown below:

Program : Android Program to Illustrate Using Custom Styles in


Android
1. Create a new Android application project with the name ‘style’.
2. Place a text view control and a button control on the layout.
3. Open ‘styles.xml’ file located in ‘values’ folder under ‘res’ folder in a text editor and
enter the following code:

<resources>
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>

<!-- Application theme. -->


<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

341
Android Lab Manual for Novice

<style name="CustomFontStyle">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>
<item name="android:textColor">#00FF00</item>/>
</style>
</resources>

Gradient.xml File
The structure of ‘gradient.xml’ layout file is shown below:

<?xml version="1.0" encoding="utf-8"?>


<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<gradient
android:angle="270"
android:centerColor="#FF207FB9"
android:endColor="#FF0060B8"
android:startColor="#FF66CFE6" />
<padding
android:bottom="8dp"
android:left="8dp"
android:right="8dp"
android:top="8dp" />
<corners android:radius="48dp" />
</shape>

The structure of ‘activity_main.xml’ layout file is shown below:

342
Android Lab Manual for Novice

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
style="@style/CustomFontStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="85dp"
android:background="@drawable/gradient"
android:text="Button" />
</RelativeLayout>

The following figure shows the project structure:

343
Android Lab Manual for Novice

On deploying the project in the emulator, the following output is generated:

344
Android Lab Manual for Novice

Program : Android Program to Illustrate Using Custom Styles in


Android
1. Create a new Android application project with the name ‘mystyle’.
2. Place an edit text control and two button controls on the layout.
3. Create the file with the name ‘mystyle.xml’ file ‘res/drawable-hdpi’ folder and enter the
following code:

<?xml version="1.0" encoding="utf-8"?>


<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="true"><shape>
<stroke android:width="2.3dp" android:color="#a7bf42" />
<corners android:radius="10dp" />
</shape></item>
<item android:state_focused="false" android:state_pressed="true"><shape>
<stroke android:width="2.3dp" android:color="#a7bf42" />
<corners android:radius="10dp" />
</shape></item>
<item android:state_focused="true" android:state_pressed="false"><shape>
<stroke android:width="0.7dp" android:color="#000000" />
<corners android:radius="15dp" />
</shape></item>
<item android:state_focused="false" android:state_pressed="false"><shape>
<gradient android:angle="270" android:centerColor="#F6EBC9"
android:endColor="#a7bf42" android:startColor="#a7bf42" />
<stroke android:width="0.7dp" android:color="#000000" />
<corners android:radius="15dp" />
</shape></item>
<item android:state_enabled="true"><shape>
<padding android:bottom="4dp" android:left="4dp" android:right="4dp"
android:top="4dp" />

345
Android Lab Manual for Novice

</shape></item>
</selector>

4. Create the file with the name ‘red.xml’ in ‘res/drawable-hdpi’ folder and enter the
following code:

<?xml version="1.0" encoding="utf-8"?>


<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape>
<solid
android:color="#ef4444" />
<stroke
android:width="1dp"
android:color="#992f2f" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="#ef4444"
android:endColor="#992f2f"
android:angle="270" />
<stroke

346
Android Lab Manual for Novice

android:width="1dp"
android:color="#992f2f" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
</selector>

5. Create the file with the name ‘rounded.xml’ in ‘res/drawable-hdpi’ folder and enter the
following code:

<?xml version="1.0" encoding="utf-8"?>


<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<!--make a gradient background-->
<gradient
android:type="linear"
android:startColor="#556B2F"
android:endColor="#BDB76B"
android:centerColor="#ffffff"
android:angle="90"
android:gradientRadius="90"
/>
<!--apply a border around button-->
<stroke android:color="#006400" android:width="2dp" />

347
Android Lab Manual for Novice

<!-- make the button corners rounded-->


<corners android:radius="25dp"/>
</shape>
</item>
</selector>

6. Set the ‘background’ properties of EditText to ‘@drawable/mystyle’, and two button


controls to ‘@drawable/red’ and ‘@drawable/rounded’, respectively.

The structure of ‘activity_main.xml’ layout file is shown below:


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="@drawable/red"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"

348
Android Lab Manual for Novice

android:layout_alignParentTop="true"
android:layout_marginTop="124dp"
android:ems="10"
android:background="@drawable/mystyle"
android:text="Define a Style and Apply to a View">
<requestFocus />
</EditText>

<Button
android:id="@+id/button1"
android:background="@drawable/red"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginLeft="90dp"
android:layout_marginTop="74dp"
android:text="Button" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="54dp"
android:background="@drawable/rounded"
android:text="Rounded Corners Gradient Button" />
</RelativeLayout>

The following figure shows the project structure:

349
Android Lab Manual for Novice

On deploying the project in the emulator, the following output is generated:

350
Android Lab Manual for Novice

Execution of the Application in Android Studio


 Expand ‘res’ folder.
 Right-click on ‘drawable’ folder and select New → File from the shortcut menu as
shown in the following figure:

The following dialog is displayed:

 Enter the file name as ‘mystyle.xml’ as shown above.


 Copy the shown earlier in ‘mystyle.xml’ file into the file created above.
 Similarly create two more files,
 red.xml and
 rounded.xml with the content shown above.

After this the ‘res/drawable’ folder looks like this:

Next, copy the code in ‘activity_main.xml’ file as shown above.

Deploy the application on a target device. The following output is generated:

351
Android Lab Manual for Novice

3.3 Creating and Using a String Array Resource in Android

3.3.1 Creating a String Array Resource in Eclipse


String array resources are located in ‘strings.xml’ file in ‘values’ sub-folder of ‘res’ folder.
For creating a new string resource double-click on ‘strings.xml’ file in ‘values’ folder under
‘res’ folder.

352
Android Lab Manual for Novice

Click on ‘Add’ button. The following dialog is displayed:

353
Android Lab Manual for Novice

Select ‘String Array’ from the list of elements displayed and click on ‘OK’ button.

Enter the name of the string array resource as ‘courses’.


With the ‘courses’ item selected, click on ‘Add’ button and add an item with a string value
‘MCA’ as shown in the following figure:

354
Android Lab Manual for Novice

Similarly add three more items with the string values, ‘MBA’, ‘MSW’, ‘M.Phil’.
After this the edit looks like this:

and the following code is generated in ‘strings.xml’ file.

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="app_name">stringarray</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string-array name="courses">
<item >MCA</item>
<item >MBA</item>
<item >M.Phil</item>
</string-array>
</resources>

355
Android Lab Manual for Novice

Testing the String Array Resource


To test the string array resource created above, open activity_main.xml file present in layout
folder, by double-clicking on it.

Drag and drop ‘ListView’ control from the ‘Composite’ tab on the layout as shown in the
following figure:

The ListView control has the property called ‘Entries’ as shown in the following figure. This
property can be initialized with string array resource.

356
Android Lab Manual for Novice

For setting ‘Entries’ property click on three ellipsis next to the property. The following dialog is
displayed. Expand ‘Array’ element and select ‘courses’ from the list displayed. Click on ‘OK’
button.

The ‘Entries’ property of ListView control is set as shown in the following figure:
357
Android Lab Manual for Novice

To test, deploy the application on the emulator. The following output is generated:

3.3.2 Creating String Resource in Android Studio


In Android Studio, there is no visual editor for creating a string array resource.
 Open ‘strings.xml’ file located under ‘res/values’ folder and enter the code manually as
shown in the following figure:
358
Android Lab Manual for Novice

 Place a ListView control located in ‘Containers’ tab on the layout.


 Click on three ellipsis next to ‘entries’ property of a Properties table of a ListView
control as shown in the following figure:

 OR enter the value ‘@array/courses’ for ‘entries’ property manually as shown in the
above figure.
 Deploy the application on target device.

The following output is generated:

359
Android Lab Manual for Novice

3.4 Creating and Using a Menu Resource in Android

3.4.1 Creating a Menu in Eclipse


In eclipse, Main Menu resource is located in ‘main.xml’ file in ‘menu’ subfolder of ‘res’ folder.

Other menu resources can be created and stored in this folder. When the new project is created in
Android by default a main menu is created. The menu resource file with the name ‘main.xml’ is
created and stored in a folder ‘res/menu’ under project folder as shown in the following figure:

360
Android Lab Manual for Novice

Double-click on ‘main.xml’ file to open it in the editor as shown below:


The main menu contains a single item with the ID ‘@+id/action_settings’ and title
‘@string/action_settings’ (which is a string resource stored in ‘res/values/strings.xml’ file) as
shown in the following figure:

361
Android Lab Manual for Novice

The content of ‘strings.xml’ file is shown below:

On deploying the project in an emulator, the following output is generated:

Modifying Main Menu


First we will modify the title ‘Settings’ to ‘New’

362
Android Lab Manual for Novice

Click on ‘New String…’

363
Android Lab Manual for Novice

Click on ‘OK’ button.

On re-deploying the project in an emulator, the following output is generated:

364
Android Lab Manual for Novice

Adding New Menu Items to Main Menu


Double-click on ‘main.xml’ file in the project explorer and click on ‘Add’ button. The following
dialog is displayed.

Select the first option ‘Create a new element at the top level, in Menu’ as shown in the above
figure, select ‘Item’ option and click on ‘OK’ button. The new menu item is added to the menu
as shown in the following figure:

365
Android Lab Manual for Novice

The default Id of the new menu item is ‘@+id/item1’. To change it to the required Id, click on
the ‘Browse..’ button next to it.
You can directly enter ID of your choice in Id text field. ‘+’ sign indicates that if the ID is not
present then it will be created.
Create the following menu items:
Menu Item ID String Resource Name String Resource Value
‘@+id/open file_open Open
‘@+id/save file_save Save

The content of ‘strings.xml’ file is as follows:

366
Android Lab Manual for Novice

All the titles of menu items are stored in ‘strings.xml’ file.

On re-deploying the project in an emulator, the following output is generated:

3.4.1.1 Creating a Submenu


Double-click on ‘main.xml’ file in Project Explorer.

367
Android Lab Manual for Novice

Click on ‘Add’ button.

Select ‘Item’ and click on ‘OK’ button. Enter the title of submenu as ‘File’.

368
Android Lab Manual for Novice

With the item selected, click on ‘Add’ button.

Select the second option ‘Create a new element in the selected element’ and click on ‘OK’
button.

369
Android Lab Manual for Novice

Select the submenu and click on ‘Add’ button.

Select ‘Item’ and click on ‘OK’ button. Enter the title of the menu item as ‘Open’.

370
Android Lab Manual for Novice

Similarly add another menu item, ‘Save’

Note: In the case of any errors, clean and build the project.

Click on ‘File’ Menu

371
Android Lab Manual for Novice

Adding ‘Edit’ Sub Menu


With ‘item1’ selected, click on ‘Add’ button.
Select ‘Item’ and click on ‘OK’ button.
With the newly added item selected, click on ‘Add’ button and select ‘SubMenu’. Click on ‘OK’
button. Add three menu items to ‘Edit’ submenu with the title, ‘Cut’, ‘Copy’ and ‘Paste’.

Now, the structure of ‘main.xml’ file is as follows:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >


<item android:id="@+id/item1" android:title="File">
<menu>
<item android:id="@+id/item2" android:title="New"/>
<item android:id="@+id/item3" android:title="Open"/>
<item android:id="@+id/item4" android:title="Save"/>
</menu>
</item>
<item android:id="@+id/item5" android:title="Edit">
<menu>
<item android:id="@+id/item6" android:title="Cut"/>
<item android:id="@+id/item7" android:title="Copy"/>
<item android:id="@+id/item8" android:title="Paste"/>
</menu>
</item>

</menu>

On deploying the application on target device, the following output is generated:

372
Android Lab Manual for Novice

On selecting the ‘File’ menu, the following output is generated:

On selecting the ‘Edit’ menu, the following output is generated:

373
Android Lab Manual for Novice

3.4.1.2 Creating Mutually Exclusive Menu Items


Double-click on ‘main.xml’ file in Package Explorer.

Click on ‘Add’ button and add an item to the menu.

374
Android Lab Manual for Novice

Enter the title as ‘Shape’.


With the item selected, click on ‘Add’ button and add a ‘submenu’.

375
Android Lab Manual for Novice

With the ‘Sub-Menu’ selected click on ‘Add’ button. The following dialog is displayed.

Select ‘Group’ and click on ‘OK’ button.

376
Android Lab Manual for Novice

With the ‘group1’ item selected, choose ‘single’ option from ‘Checkable behavior’ drop-down
list.
With the ‘group1’ selected, click on ‘Add’ button and add an item with title ‘Line’ as shown
below:

Similarly, add two more items, ‘Circle’ and ‘Rectangle’.


After this, the editor looks like this:

377
Android Lab Manual for Novice

and the following code is generated:


<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/item1" android:title="Shape">
<menu>
<group android:id="@+id/group1" android:checkableBehavior="single">
<item android:id="@+id/item2" android:title="Line"/>
<item android:id="@+id/item3" android:title="Circle"/>
<item android:id="@+id/item4" android:title="Rectangle"/>
</group>
</menu>
</item>
</menu>

On deploying the application on target device, the following output is generated:

On clicking the ‘Shape’ menu, the following output is generated:

378
Android Lab Manual for Novice

Specifying a default item.


With the ‘Line’ menu item selected, set the ‘Checked’ property to ‘true’ as shown in the
following figure:

On deploying the application on target device, the following output is generated:

379
Android Lab Manual for Novice

The code generated in ‘main.xml’ file is shown below:


<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/item1" android:title="Shape">
<menu>
<group android:id="@+id/group1" android:checkableBehavior="single">
<item android:id="@+id/item2" android:title="Line" android:checked="true"/>
<item android:id="@+id/item3" android:title="Circle"/>
<item android:id="@+id/item4" android:title="Rectangle"/>
</group>
</menu>
</item>
</menu>

In the above code change the ‘android:checkableBehaviour’ to ‘all’. On deploying the


application in emulator, the following output is generated:

380
Android Lab Manual for Novice

Creating Menu Resource in Eclipse


For creating a new menu resource follow the steps enumerated below:
1. Right-click on ‘menu’ folder under ‘res’ folder and select New → Android XML File
from the shortcut menu as shown below:

2. Enter the name of the menu as ‘shape_menu’ and click on ‘Finish’ button.

381
Android Lab Manual for Novice

‘shape_menu.xml’ file is generated in ‘menu’ folder as shown below:

382
Android Lab Manual for Novice

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/item1" android:title="Line"></item>
<item android:id="@+id/item2" android:title="Circle"></item>
<item android:id="@+id/item3" android:title="Rectangle"></item>
</menu>

Attaching a Menu to MainActivity


Modify the MainActivity class as shown below. The modified statement is shown in bold italic.
package com.example.menu_create;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

383
Android Lab Manual for Novice

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.shape_menu, menu);
return true;
}

384
Android Lab Manual for Novice

3.4.2 Creating a Menu in Android Studio


Right-click on the ‘res’ folder and select New → Directory from the shortcut menu as shown in
the following figure:

Enter new directory name as ‘menu’ as shown below:

Right-click on ‘menu’ node and select New → Menu resource file from shortcut menu.

385
Android Lab Manual for Novice

Enter the name of the resource file as ‘main_menu’ and click on ‘OK’ button.

The palette contains the following items for creating the menu,

386
Android Lab Manual for Novice

 Menu Item
 Menu
 Group

The component tree contains main menu as shown in the following figure:

For adding menu items to the main menu, drag the menu item from the palette and drop it onto
the menu inside component tree. The GUI is updated accordingly as shown in the following
figure:

387
Android Lab Manual for Novice

Select the menu item in the layout and in the properties table enter the ‘id’ and ‘title’ for the
menu as shown in the following figure:

The two required properties of menu item are ‘id’ and ‘title’.

388
Android Lab Manual for Novice

Similarly create other menu items using the ‘id’ and ‘title’ shown in the following table:

Menu ID Menu Title


item1 New
item2 Open
item3 Save
item4 Exit

After this the component tree looks like this:

The code generated and stored in ‘main_menu.xml’ file is shown in the following figure:

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="New"
android:id="@+id/item1" />
<item android:title="Open"
android:id="@+id/item2" />

389
Android Lab Manual for Novice

<item android:title="Save"
android:id="@+id/item3" />
<item android:title="Exit" />
</menu>

Add the following method to MainActivity class:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}

On deploying the project on a target device, the following output is generated:

390
Android Lab Manual for Novice

Note: The order of menu items can be changed by dragging and dropping the menu item to the
required location in component tree.

3.4.2.1 Creating Checked and Disabled Menu Items


 Create a new project with the name ‘Menu’ in Android Studio.
 Create a menu resource with name ‘main_menu’ under ‘res/menu’ folder as described
earlier.
 Create three menu items as shown below:
o Create a menu item with id ‘item1’ and title ‘Enabled’ and set the properties as
shown below:

o Create a menu item with id ‘item2’ and title ‘Checked’ and set the properties as
shown below:

391
Android Lab Manual for Novice

o Create a menu item with id ‘item3’ and title ‘disabled’ and set the properties as
shown below:

Note: ‘-‘ in the property indicates that the property is not set.
Add onCreateOptionsMenu() method to MainActivity class.
On deploying the application on target device, the following output is generated:

392
Android Lab Manual for Novice

3.4.2.2 Creating a Sub Menu in Android Studio


Drag and drop the ‘menu’ on ‘item1’ to convert it into a submenu. Next, drag and drop the menu
items on the sub menu as shown in the following figure:

The following code is generated:

On execution on the application the following output is generated.

393
Android Lab Manual for Novice

On opening the sub menu, the following output is generated:

394
Android Lab Manual for Novice

Creating Edit Sub Menu


For creating a second sub menu, ‘Edit’ follow the steps enumerated below:

 Drag and drop a menu item on ‘menu’ in component tree. Change it’s ‘Text’ property to
‘Edit’.
 Drag and drop a menu on ‘Edit’ menu.
 Drag and drop three menu items on ‘Edit’ menu and set their ids and titles as shown in
the following table:

Menu ID Menu Title


Item5 Cut
Item6 Copy
Item7 Paste

After this, the component tree looks like the one shown in the following figure:

The structure of auto generated ‘main_menu.xml’ file is as follows:

395
Android Lab Manual for Novice

main_menu.xml

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">

<item android:title="File"
android:id="@+id/item1" >
<menu >
<item android:title="New"
android:id="@+id/item1"
android:visible="true"
android:showAsAction="always" />
<item android:title="Open"
android:id="@+id/item2"
android:visible="true"
android:showAsAction="always" />
<item android:title="Save"
android:id="@+id/item3"
android:visible="true"
android:showAsAction="always" />
<item android:title="Exit"
android:id="@+id/item4"
android:visible="true"
android:showAsAction="always" />
</menu>
</item>
<item android:title="Edit" >
<menu >
<item android:title="Cut"

396
Android Lab Manual for Novice

android:id="@+id/item5" />
<item android:title="Copy"
android:id="@+id/item6" />
<item android:title="Paste"
android:id="@+id/item7" />
</menu>
</item>
</menu>

On deploying the project on target device, the following output is produced.

On selecting ‘File’ menu, the following output is generated:

397
Android Lab Manual for Novice

On selecting ‘Edit’ menu, the following output is generated:

398
Android Lab Manual for Novice

Adding Icons to the Menu Items in Android Studio


For adding icon to the menu item, set the following properties:

showAsAction – always

icon - @drawable/exit

Click on the ellipsis next to icon text field and select the image from the ‘drawable’ folder as
shown in the following figure:

Place a check mark next to ‘visible’ and select icon.

399
Android Lab Manual for Novice

The following code is generated for adding an icon to the menu item:

On execution of the application, the following output is generated:

400
Android Lab Manual for Novice

3.4.2.3 Creating Mutually Exclusive Menu Items


The palette contains an item with the name ‘Group’ which is used for creating mutually
exclusive or multiple selection menu items. The ‘Group’ item has a property with the name
‘checkableBehavior’ which can take one of the following two values:
 ‘single’ for mutually exclusive items
 ‘all’ for enabling multiple selections

The ‘MenuItem’ control has the following properties:


 Checkable – true for displaying checkbox next to the menu item
 Checked – For initially selecting the menu item

In the current example, we will create a group of mutually exclusive shape menu items.
 Create a new project in Android Studio with the name ‘MenuGroup’.
 Create a ‘menu’ folder under ‘res’ folder and create a new menu resource file with the
name ‘main_menu.xml’.
 Drag and drop ‘group’ item from the palette on the menu.
 Drag and drop three menu items on ‘group’ item of component tree and set their ids and
titles as shown in the following table:

Menu ID Menu Title


Item1 Line
Item2 Circle
Item3 Rectangle

The structure of the component tree is as shown in the following figure:

401
Android Lab Manual for Novice

The auto-generated ‘main_menu.xml’ file is shown below:

main_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single" >
<item android:title="Line"
android:id="@+id/item1"
android:checked="true"
/>
<item android:title="Circle"
android:id="@+id/item2"/>
<item android:title="Rectangle"
android:id="@+id/item3"/>
</group>
</menu>

On deploying the application in the emulator, the following output is generated:

402
Android Lab Manual for Novice

In the ‘main_menu.xml’ file change ‘android:checkableBehavior’ property to ‘all’.


On re-deploying the project on the target device, the following output is generated

403
Android Lab Manual for Novice

3.4.2.4 Creating Multiple Selection Menu Items


Multiple menu items can be selected from a menu by setting the ‘checkableBehavior’ property
of a group to ‘all’.
1. Drag and drop Menu Item from palette on item ‘menu’ of component tree.
2. Change its ‘Text’ property to ‘Shape’.
3. Drag and drop Menu Item from palette on ‘Shape’ item in a component tree.
4. Drag and drop Group from palette on item ‘menu’ of component tree.
5. Select a group and in the ‘Properties’ table of a Group set ‘CheckableBehavior’ to ‘all’
as shown in the following figure:

6. Drag and drop three items on the group as depicted in the following table:
Menu ID Menu Title
Item1 Line
Item2 Circle
Item3 Rectangle

7. Set the ‘checkable’ property to ‘true’ for all items.


8. Set the ‘checked’ property to ‘true’ for the ‘Line’ item.

The property settings for the three menu items are shown in the following figures:

404
Android Lab Manual for Novice

The structure of a component tree is shown in the following figure:

405
Android Lab Manual for Novice

The code generated in ‘main_menu.xml’ file is shown below:

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:title="Shape" >


<menu >
<group android:checkableBehavior="all" />
<item android:title="Line"
android:id="@+id/item1"
android:checkable="true"
android:checked="true" />
<item android:title="Circle"
android:id="@+id/item2"
android:checkable="true" />
<item android:title="Rectangle"
android:id="@+id/item3"
android:checkable="true" />
</menu>
</item>

406
Android Lab Manual for Novice

On deploying the project on a target device, the following output is generated:

On clicking ‘Shape’ menu, the following output is generated:

407
Android Lab Manual for Novice

3.4.2.5 Creating Menu Hierarchy of Mutually Exclusive Items


In the current example, we will create two sub menus with the title ‘Shape’ and ‘Color’
containing mutually exclusive menu items.
 Create a new project in Android Studio with the name ‘MenuGroup’.
 Create a ‘menu’ folder under ‘res’ folder and create a new menu resource file with the
name ‘main_menu.xml’.
 Drag and drop a ‘Menu Item’ from palette on ‘menu’ in component tree and set its
‘Text’ property to ‘Shape’.
 Drag and drop a ‘Menu’ from palette on ‘Shape’ in component tree.
 Drag and drop a ‘Group’ from palette on ‘menu’ item below ‘Shape’ in component tree.
 Drag and drop three menu items on ‘group’ item of component tree and set their ids and
titles as shown in the following table:

Menu ID Menu Title


Item1 Line
Item2 Circle
Item3 Rectangle

 Drag and drop a ‘Menu Item’ from palette on ‘menu’ in component tree and set its
‘Text’ property to ‘Color’.
 Drag and drop a ‘Menu’ from palette on ‘Color’ in component tree.
 Drag and drop a ‘Group’ from palette on ‘menu’ item below ‘Color’ in component tree.
 Drag and drop three menu items on ‘group’ item item below ‘Color’ item in component
tree and set their ids and titles as shown in the following table:

Menu ID Menu Title


Item4 Red
Item5 Green
Item6 Blue

408
Android Lab Manual for Novice

The structure of the component tree is as shown in the following figure:

The structure of the auto-generated ‘main_menu.xml’ file is shown below:


main_menu.xml


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Shape" >
<menu >
<group android:checkableBehavior="single" >
<item android:title="Line"
android:id="@+id/item1"
android:checked="true" />
<item android:title="Circle"
android:id="@+id/item2" />
<item android:title="Rectangle"
android:id="@+id/item3" />
</group>

409
Android Lab Manual for Novice

</menu>
</item>
<item android:title="Color" >
<menu >
<group android:checkableBehavior="single">
<item android:title="Red"
android:id="@+id/item4"
android:checked="true" />
<item android:title="Green"
android:id="@+id/item5" />
<item android:title="Blue"
android:id="@+id/item6" />
</group>
</menu>
</item>
</menu>

Deploy the project on a target device. The following output is generated:

410
Android Lab Manual for Novice

On selecting the ‘Shape’ menu, the following output is generated:

On selecting the ‘Color’ menu, the following output is generated:

411
Android Lab Manual for Novice

Change the ‘checkableBehaviour’ property to ‘all’.


On re-deploying the project on the target device and selecting ‘Shape’ menu, the following
output is generated:

On selecting the ‘Color’ menu, the following output is generated:

412
Android Lab Manual for Novice

Example:
Creating Course and Language Menus
The component trees of ‘course_menu’ and ‘language_menu’ are shown in the following
figures:

The structure of ‘MainActivity.java’ file is shown below:

MainActivity.java

package com.example.lenovo1.custommenu;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

413
Android Lab Manual for Novice

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.course_menu, menu);
getMenuInflater().inflate(R.menu.language_menu, menu);
return true;
}
}

On deploying the project on the target device the following output is generated:

Comment the line

getMenuInflater().inflate(R.menu.course_menu, menu);

414
Android Lab Manual for Novice

and uncomment the line


getMenuInflater().inflate(R.menu.language_menu, menu);

in ‘MainActivity.xml’ file.

On re-deploying the application on target device, the following output is generated:

415
Android Lab Manual for Novice

CHAPTER 4
Working with Dialogs in Android
‘android.widget’ package supports the following dialog classes for improving the user
experience of an end user:
 AlertDialog
 DatePickerDialog
 TimePickerDialog
 ProgressDialog
 CharacterPickerDialog

The current chapter discusses these dialogs in depth.

4.1 AlertDialog in Android

• Android AlertDialog class can be used to display the dialog message with ‘OK’ and
‘Cancel’ buttons. It can be used to interrupt and ask the user about his/her choice to
continue or discontinue.
• Android AlertDialog is composed of three regions: title, content area and action buttons.

Android ‘AlertDialog’ class is the subclass of ‘Dialog’ class. The following figure depicts
the hierarchy of AlertDialog class.

416
Android Lab Manual for Novice

Methods of AlertDialog.Builder class


The following table enlists the important methods of ‘AlertDialog’ class:

Method Description
setTitle(CharSequence) This method is used to set the title of
AlertDialog.
setMessage(CharSequence) This method is used to set the message of
AlertDialog.
setIcon(int) This method is used to set the icon of
AlertDialog with the specified icon ID as
parameter.

Steps in Creating AlertDialog


The important steps involved in creating an AlterDialog class are enumerated below:
1. Create an object of AlertDialog.Builder class as shown below:
AlertDialog.Builder alertdialog= new AlertDialog.Builder(this);
2. Set the title of dialog and message to be displayed using setTitle() and setMessage()
methods of AlertDialog.Builder class.
3. Customize the dialog by specifying the buttons to be displayed on the dialog using
setPositiveButton() and setNeutralButton() methods of AlertDialog.Builder class. These
methods accept two parameters, the first parameter is the caption to be displayed on the
button and the second parameter is an instance of event listener class.
4. Create an instance of ‘AlertDialog’ class by invoking create() method of
AlertDialog.Builder class as shown below:
AlertDialog alert=alertdialog.create();
5. Display the alert dialog using show() method of AlertDialog() class.
alert.show();

Program : Android Program to illustrate Alert Dialog in Android.


1. Create a new Android application project with the name ‘alertdialog’.
2. Place a single button control on the layout.

417
Android Lab Manual for Novice

3. Change the ‘Text’ property of button control to ‘Display dialog’.


4. Declare the following data members in MainActivity class

AlertDialog.Builder alertdialog;

5. Add the following method to MainActivity class.

public void display(View v)


{
alertdialog = new AlertDialog.Builder(this);
alertdialog.setTitle("Test");
alertdialog.setMessage("Continue?");
alertdialog.setPositiveButton("OK", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"You Clicked on
OK",Toast.LENGTH_LONG).show();
}
});
alertdialog.setNeutralButton("Cancel", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertdialog.create();
alertdialog.show();
}

6. Add the following attribute to <button> element in ‘activity_main.xml’ file.


android:onClick=”display”

The complete source code of MainActivity class is given below:

418
Android Lab Manual for Novice

MainActivity.java

package com.example.alertdialog;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {


AlertDialog.Builder alertdialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void display(View v)
{
alertdialog = new AlertDialog.Builder(this);
alertdialog.setTitle("Test");
alertdialog.setMessage("Continue?");
alertdialog.setPositiveButton("OK", new AlertDialog.OnClickListener() {

419
Android Lab Manual for Novice

public void onClick(DialogInterface dialog, int which) {


Toast.makeText(MainActivity.this,"You Clicked on OK",
Toast.LENGTH_LONG).show();
}
});
alertdialog.setNeutralButton("Cancel", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertdialog.create();
alertdialog.show();
}
}

The structure of ‘activity_main.xml’ layout file is shown below:


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"

420
Android Lab Manual for Novice

android:layout_height="wrap_content"
android:text="Alert Dialog Demo"
android:textSize="25sp" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginRight="60dp"
android:layout_marginTop="58dp"
android:text="Exit"
android:onClick="display"/>
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

On clicking ‘OK’ button, the following output is generated:


421
Android Lab Manual for Novice

Execution of Application in Android Studio


On execution of the application in Android Studio, the following output is generated:

422
Android Lab Manual for Novice

423
Android Lab Manual for Novice

4.2 DatePickerDialog in Android


Program : Android Program to illustrate DatePickerDialog in Android.
Steps in Creating and Using DatePickerDialog
1. Create an object of DatePickerDialog by invoking a 5 argument constructor.
 The first parameter is MainActivity class reference.
 The second parameter is an object of listener class implementing
OnDateSetListener interface.
 The third, fourth and fifth parameters are year, month and day components of the
selected date.

2. Invoke ‘show()’ method of DatePickerDialog class to make it visible.


3. Create a listener class by implementing ‘OnDateSetListener’ interface providing
implementation for onDateSet() method.

The following program demonstrates using DatePickerDialog class in Android


1. Create a new Android application project with the name ‘datepicker1’.
2. Place a single text view control and a button control on the layout.
3. Change the ‘Text’ property of button control to ‘SetDate’.
4. Declare the following data members in MainActivity class

private TextView t;
private Button b;
private int year, month, day;

5. Append the following text to onCreate() method of MainActivity class

t=(TextView) findViewById(R.id.textView1);
b=(Button) findViewById(R.id.button1);
final Calendar c= Calendar.getInstance();

424
Android Lab Manual for Novice

year=c.get(Calendar.YEAR);
month=c.get(Calendar.MONTH);
day=c.get(Calendar.DAY_OF_WEEK);
t.setText("Current Date is : "+(month+1)+"-"+day+"-"+year);
b.setOnClickListener(this);

6. Add the following method to MainActivity class.

public void onClick(View arg0) {


new
DatePickerDialog(MainActivity.this,dateListener,year,month,day).show();

7. Add the following data member initialization to MainActivity class

private DatePickerDialog.OnDateSetListener dateListener = new


DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int tyear, int tmonth, int tday) {
year=tyear;
month=tmonth;
day=tday;
t.setText("Current Date is : "+(month+1)+"-"+day+"-"+year);
}
};

The complete source code of MainActivity class is given below:

425
Android Lab Manual for Novice

MainActivity.java

package com.example.datepicker1;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{


private TextView t;
private Button b;
private int year, month, day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(TextView) findViewById(R.id.textView1);
b=(Button) findViewById(R.id.button1);
final Calendar c= Calendar.getInstance();
year=c.get(Calendar.YEAR);
month=c.get(Calendar.MONTH);
day=c.get(Calendar.DAY_OF_WEEK);
t.setText("Current Date is : "+(month+1)+"-"+day+"-"+year);
b.setOnClickListener(this);
}

426
Android Lab Manual for Novice

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View arg0) {
new DatePickerDialog(MainActivity.this,dateListener,year,month,day).show();

private DatePickerDialog.OnDateSetListener dateListener = new


DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int tyear, int tmonth, int tday) {
year=tyear;
month=tmonth;
day=tday;
t.setText("Current Date is : "+(month+1)+"-"+day+"-"+year);
}
};
}

Method 2:
The complete source code of MainActivity class is given below:
MainActivity.java

package com.example.datepicker2;
import java.util.Calendar;
import android.os.Bundle;

427
Android Lab Manual for Novice

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener, OnDateSetListener{


private TextView t;
private Button b;
private int year, month, day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(TextView) findViewById(R.id.textView1);
b=(Button) findViewById(R.id.button1);
final Calendar c= Calendar.getInstance();
year=c.get(Calendar.YEAR);
month=c.get(Calendar.MONTH);
day=c.get(Calendar.DAY_OF_WEEK);
t.setText("Current Date is : "+(month+1)+"-"+day+"-"+year);
b.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.

428
Android Lab Manual for Novice

getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public void onClick(View arg0) {
new DatePickerDialog(MainActivity.this,this,year,month,day).show();

@Override
public void onDateSet(DatePicker arg0, int tyear, int tmonth, int tday) {
year=tyear;
month=tmonth;
day=tday;
t.setText("Current Date is : "+(month+1)+"-"+day+"-"+year);
}
}

The structure of ‘activity_main.xml’ layout file is shown below:


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

429
Android Lab Manual for Novice

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp"
android:textSize="20sp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:text="Set Date" />
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

430
Android Lab Manual for Novice

Execution of the Application in Android Studio


On executing the application in Android Studio, the following output is generated:

431
Android Lab Manual for Novice

Click on ‘Display Date’ button. The ‘Date Picker’ dialog with the current date selected, is
displayed as shown in the following figure.

Select the required date and click on ‘OK’ button. The selected date is displayed in a text view
control as shown in the following figure:

432
Android Lab Manual for Novice

4.3 TimePickerDialog in Android


Program : Android Program to illustrate TimePickerDialog in Android.
Steps in Creating and Using TimePickerDialog
1. Create an object of TimePickerDialog by invoking a 5 argument constructor.
 The first parameter is MainActivity class reference.
 The second parameter is an object of listener class implementing
OnTimeSetListener interface.
 The third and fourth parameters are hour and minute components of the time to be
selected.
 The fifth parameter is a boolean parameter if true displays TimePickerDialog in
24 Hour Format, otherwise displays in 12 Hour Format.

2. Invoke ‘show()’ method of TimePickerDialog class to make it visible.


3. Create a listener class by implementing ‘OnTimeSetListener’ interface providing
implementation for onTimeSet() method.

The following program demonstrates using TimePickerDialog in Android.


1. Create a new Android application project with the name ‘timepicker’.
2. Add a single text view control and a button control to the layout.
3. Change the ‘Text’ property of button control to ‘Set Time’.
4. Declare the following data members in MainActivity class

private TextView t;
private Button b;
private int hr, min;

5. Append the following text to onCreate() method of MainActivity class

t=(TextView) findViewById(R.id.textView1);

433
Android Lab Manual for Novice

b=(Button) findViewById(R.id.button1);
final Calendar c= Calendar.getInstance();
hr=c.get(Calendar.HOUR_OF_DAY);
min=c.get(Calendar.MINUTE);
t.setText("Current Time is : "+hr+":"+min);
b.setOnClickListener(this);

6. Add the following method to MainActivity class.

public void onClick(View arg0) {


new TimePickerDialog(MainActivity.this,timeListener,hr,min,true).show();
}

7. Add the following data member initialization to MainActivity class

private TimePickerDialog.OnTimeSetListener timeListener = new


TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker arg0, int hour, int minute) {
hr=hour;
min=minute;
t.setText("Current Time is : "+hr+":"+min);
}
};

The complete source code of MainActivity class is given below:


MainActivity.java

package com.example.timepicker;
import java.util.Calendar;
import android.os.Bundle;

434
Android Lab Manual for Novice

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

public class MainActivity extends Activity implements OnClickListener{


private TextView t;
private Button b;
private int hr, min;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(TextView) findViewById(R.id.textView1);
b=(Button) findViewById(R.id.button1);
final Calendar c= Calendar.getInstance();
hr=c.get(Calendar.HOUR_OF_DAY);
min=c.get(Calendar.MINUTE);
t.setText("Current Time is : "+hr+":"+min);
b.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.

435
Android Lab Manual for Novice

getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public void onClick(View arg0) {
new TimePickerDialog(MainActivity.this,timeListener,hr,min,true).show();
}

private TimePickerDialog.OnTimeSetListener timeListener = new


TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker arg0, int hour, int minute) {
hr=hour;
min=minute;
t.setText("Current Time is : "+hr+":"+min);
}
};
}

Method 2:
The complete source code of ‘MainActivity’ class is given below:

MainActivity.java

package com.example.timepicker;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;

436
Android Lab Manual for Novice

import android.app.TimePickerDialog.OnTimeSetListener;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

public class MainActivity extends Activity implements OnClickListener,OnTimeSetListener{


private TextView t;
private Button b;
private int hr,min;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(TextView) findViewById(R.id.textView1);
b=(Button) findViewById(R.id.button1);
final Calendar c= Calendar.getInstance();
hr=c.get(Calendar.HOUR_OF_DAY);
min=c.get(Calendar.MINUTE);
t.setText("Current Time is : "+hr+":"+min);
b.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;

437
Android Lab Manual for Novice

@Override
public void onClick(View arg0) {
new TimePickerDialog(MainActivity.this,this,hr,min,true).show();
}

@Override
public void onTimeSet(TimePicker arg0, int hour, int minute) {
hr=hour;
min=minute;
t.setText("Current Time is : "+hr+":"+min);
}
}

The structure of ‘activity_main.xml’ layout file is shown below:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"

438
Android Lab Manual for Novice

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="56dp"
android:textSize="20sp" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:text="Set Time" />
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

439
Android Lab Manual for Novice

Select the time and click on ‘Done’ button. The following output is generated:

On changing the fifth parameter of TimePickerDialog() constructor to ‘false’ and re-deploying


the project on the target device, the following output is generated:

440
Android Lab Manual for Novice

Execution of the Application in Android Studio


On executing the application in Android Studio, the following output is generated:

441
Android Lab Manual for Novice

On changing the fifth parameter of TimePickerDialog() constructor to ‘false’ and re-deploying


the project on the target device, the following output is generated:

442
Android Lab Manual for Novice

4.4 ProgressDialog in Android


Steps in Creating and Using ProgressDialog
1. Place a single button control on the layout with the caption ‘Download’.
2. Add the following attribute to <button> element in ‘activity_main.xml’ file.
android:onClick=’download’
3. Create an object of ProgressDialog by invoking a one argument constructor by passing
MainActivity class reference.
progress=new ProgressDialog(this);
4. Set the message and progress style of the dialog by invoking setMessage() and
setProgressStyle() methods of ProgressDialog class.
5. Create a Thread class object and implement the thread procedure in run() method by
invoking setProgress() method of ProgressDialog in a loop till it reaches 100.
6. Start the thread in the click event handler of a button control.

Program : Android Program to illustrate Progress Bar Dialog in Android.


1. Create a new Android application project with the name ‘progressbar’.
2. Place a single button control on the layout.
3. Change the ‘Text’ property of a button control to ‘Download’.
4. Declare the following data members in MainActivity class

Button b1;
private ProgressDialog progress;

5. Add the following method to MainActivity class

public void download(View view){


progress=new ProgressDialog(this);
progress.setMessage("Downloading Music");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

443
Android Lab Manual for Novice

//progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.setProgress(0);
progress.show();

final int totalProgressTime = 100;


final Thread t = new Thread() {
@Override
public void run() {
int jumpTime = 0;

while(jumpTime < totalProgressTime) {


try {
sleep(200);
jumpTime += 5;
progress.setProgress(jumpTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
t.start();
}

The complete source code of ‘MainActivity’ class is given below:

MainActivity.java

package com.example.progressbar;

444
Android Lab Manual for Novice

import android.os.Bundle;
public class MainActivity extends Activity {
Button b1;
private ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

public void download(View view){


progress=new ProgressDialog(this);
progress.setMessage("Downloading Music");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.setProgress(0);
progress.show();

final int totalProgressTime = 100;


final Thread t = new Thread() {
@Override
public void run() {
int jumpTime = 0;

445
Android Lab Manual for Novice

while(jumpTime < totalProgressTime) {


try {
sleep(200);
jumpTime += 5;
progress.setProgress(jumpTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
t.start();
}
}

The structure of ‘activity_main.xml’ layout file is shown below:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

446
Android Lab Manual for Novice

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="106dp"
android:text="Download"
android:onClick="download" />
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

On clicking ‘Download’ button, the following output is generated:

447
Android Lab Manual for Novice

Uncomment the line


progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);

and comment the line

progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

On re-deploying the project in the emulator, the following output is generated:

448
Android Lab Manual for Novice

Execution of the Application in Android Studio


 Launch Android Studio
 Create a new project with the name ‘ProgressBar’ containing empty activity.
 Place a single button control on the layout and change its ‘Text’ property to ‘Download’.
 Modify MainActivity class as shown above.
 Deploy the application on target device.

The following output is generated:

Click on ‘DOWNLOAD’ button to display progress bar as shown in the following figure:

449
Android Lab Manual for Novice

Comment the line


progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

and uncomment the line


progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);

Redeploy the application on the target device. Now, the following output is generated:

450
Android Lab Manual for Novice

Using ProgressDialog in Android


1. Create a new Android application project with the name ‘progressdialog’.
2. Add a single button control to the layout.
3. Change the ‘Text’ property of button control to ‘Start’.
4. Declare the following data members in MainActivity class

Button button;
ProgressDialog progressDialog;

5. Append the following code to onCreate() method of MainActivity class.

button = (Button) findViewById(R.id.button1);


button.setOnClickListener(new View.OnClickListener() {

451
Android Lab Manual for Novice

@Override
public void onClick(View v) {
progressDoalog = new ProgressDialog(MainActivity.this);
progressDoalog.setMax(100);
progressDoalog.setMessage("Its loading....");
progressDoalog.setTitle("ProgressDialog bar example");
progressDoalog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDoalog.show();
new Thread(new Runnable() {
@Override
public void run() {
try {
while (progressDoalog.getProgress() <= progressDoalog
.getMax()) {
Thread.sleep(200);
handle.sendMessage(handle.obtainMessage());
if (progressDoalog.getProgress() == progressDoalog
.getMax()) {
progressDoalog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();

6. Add the following variable initialization to MainActivity class.

Handler handle = new Handler() {

452
Android Lab Manual for Novice

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
progressDoalog.incrementProgressBy(1);
}
};
});

The complete source code of ‘MainActivity’ class is given below:

MainActivity.java

package com.example.progressdialog;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

Button button;
ProgressDialog progressDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

453
Android Lab Manual for Novice

setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMax(100);
progressDialog.setMessage("Its loading....");
progressDialog.setTitle("ProgressDialog bar example");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
new Thread(new Runnable() {
@Override
public void run() {
try {
while (progressDialog.getProgress() <= progressDialog
.getMax()) {
Thread.sleep(200);
handle.sendMessage(handle.obtainMessage());
if (progressDialog.getProgress() == progressDialog
.getMax()) {
progressDialog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}

454
Android Lab Manual for Novice

Handler handle = new Handler() {


@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
progressDialog.incrementProgressBy(1);
}
};
});
}
}

The structure of ‘activity_main.xml’ layout file is shown below:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

455
Android Lab Manual for Novice

android:text="@string/hello_world" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="34dp"
android:layout_toRightOf="@+id/textView1"
android:text="Start" />
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

456
Android Lab Manual for Novice

On clicking ‘Start’ button, the following output is generated:

Execution of the Application in Android Studio


 Launch Android Studio
 Create a new project with the name ‘ProgressDialog’ containing empty activity.
 Place a single button control on the layout and change its ‘Text’ property to ‘Start’.
 Modify MainActivity class as shown above.
 Deploy the application on target device.

The following output is generated:

457
Android Lab Manual for Novice

Click on ‘START’ button to display progress dialog as shown below:

458
Android Lab Manual for Novice

4.5 Using Character Picker Dialog in Android


Steps in Creating and Using CharacterPickerDialog
1. Create an object of CharacterPickerDialog class by invoking a 5 argument constructor:
 The first parameter is a reference to the MainActivity class.
 The second parameter is a View class object reference initialized with the button
of CharacterPickerDialog clicked by the user.
 The third parameter is reference to an Editable control, null if not required
 The fourth parameter is a string specifying the buttons to be place on the
CharacterDialog.
 The fifth parameter is a boolean parameter, ‘true’ means inserts a character and
‘false’ means replaces a character.

2. Implement onClick() method of CharacterPickerDialog. The prototype of onClick()


method is:
public void onClick(View v);

The parameter to onClick() method is View class object reference initialized with the button of
CharacterPickerDialog clicked by the user. To obtain the title of the button clicked by the user,
the View object must first be cast to a Button class and invoke getText() method as shown in the
following code snippet:
Button b=(Button)v;
String title=b.getText().toString();

The following program demonstrates using CharacterPickerDialog class.


1. Create a new Android application project with the name ‘characterpickerdialog’.
2. Place a single button control on the layout.
3. Change the ‘Text’ property of button control to ‘Select Character’.
4. Declare the following data members in MainActivity class

private CharacterPickerDialog dialog = null;

459
Android Lab Manual for Novice

String options = "0123456789ABCDEFGHIJ";

5. Append the following text to onCreate() method of MainActivity class

Button button = (Button) this.findViewById(R.id.button1);


button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.show();
}
});
dialog = new CharacterPickerDialog(this, new View(this), null, options,
true) {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"onClick! " +
((Button) v). getText().toString(), Toast.LENGTH_SHORT).show();
dismiss();

The complete source code of ‘MainActivity’ class is given below:

MainActivity.java

package com.example.characterpickerdialog;
import android.app.Activity;
import android.os.Bundle;
import android.text.method.CharacterPickerDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Toast;

460
Android Lab Manual for Novice

public class MainActivity extends Activity {


private CharacterPickerDialog dialog = null;
String options = "0123456789ABCDEFGHIJ";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button button = (Button) this.findViewById(R.id.button1);


button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.show();
}
});
dialog = new CharacterPickerDialog(this, new View(this), null, options,
true) {
public void onClick(View v) {

Toast.makeText(getApplicationContext(), "onClick! " +


((Button) v).getText().toString(), Toast.LENGTH_SHORT).show();
dismiss();
}

public void onItemClick(AdapterView parent, View view,


int position, long id) {
dismiss();
}
};

461
Android Lab Manual for Novice

}
}

The structure of ‘activity_main.xml’ layout file is shown below:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="103dp"
android:text="Select Character" />
</RelativeLayout>

On deploying the project in the emulator, the following output is generated:

462
Android Lab Manual for Novice

On clicking ‘Select Character’ button, the Character Picker dialog is displayed as shown below:

463
Android Lab Manual for Novice

On selecting a character, the following output is produced:

Execution of the Application in Android Studio


 Launch Android Studio
 Create a new project with the name ‘CharacterPickerDialog’ containing empty activity.
 Place a single button control on the layout and change its ‘Text’ property to ‘Select
Character’.
 Modify MainActivity class as shown above.
 Deploy the application on target device.

The following output is generated:

464
Android Lab Manual for Novice

On clicking ‘Select Character’ button, the following output is generated:

465
Android Lab Manual for Novice

Click on any character, the selected character is displayed in a Toast as shown below:

466
Android Lab Manual for Novice

References:
Learning Resources:.

1. http://developer.android.com/guide/developing/tools/avd.html
2. http://developer.android.com/guide/developing/tools/emulator.html
3. http://developer.android.com/tools/sdk/tools-notes.html
4. http://www.qemu.org
5. https://developer.android.com/tools/revisions/build-tools.html
6. http://developer.android.com/guide/developing/tools/index.html
7. http://developer.android.com/guide/developing/tools/layoutopt.html.
8. https://developer.android.com/google/play-services/index.html
9. https://developer.android.com/tools/support-library/index.html
10. http://developer.android.com/guide/developing/tools/monkey.html.
11. https://www.tutorialspoint.com/android/index.htm
12. https://developer.android.com/guide
13. https://www.javatpoint.com/android-tutorial
14. https://www.studytonight.com/android
15. https://www.tutlane.com/tutorial/android
16. https://www.vogella.com/tutorials/android.html
17. https://www.w3school.in/android-studio/
18. https://examples.javacodegeeks.com/android/android-tutorial-beginners-with-examples/
19. https://abhiandroid.com/programming/
20. https://developer.android.com/reference/android/view/WindowManager.LayoutParams
21. http://developer.android.com/guide/developing/tools/adb.html#shellcommands.
22. http://developer.android.com/guide/developing/tools/zipalign.html.
23. http://developer.android.com/guide/developing/tools/draw9patch.html.
24. http://developer.android.com/guide/developing/other-ide.html#CreatingAProject.

467
This book is intended for a novice who is keen in getting first-hand information
about Android. The book is thought provoking which motivates the reader to
think out of the box and explore new features available in the application
framework.
The book is written in-line with the industry requirements and consists of 4
chapters from chapter 1 through 4.
Chapter 1 focuses on basic features and architecture of Android and provides
insight into execution of Android application. The main feature of the chapter
is setting up development environment which focuses on setting up ADT
bundled eclipse and Android Studio. Android application folder structure is
explored at depth. Downloading Android platforms and creating AVD for
testing Android applications are also discussed. Chapter concludes with
discussion of command-line tools, Android Debug Bridge (ADB), Activity
Manager and Package Manager.
Chapter 2 is devoted for basic building blocks of Android, core Android libraries
and different types of layouts understanding of which is crucial for developing
working application in Android. Anatomy of Android application is presented.
The structure of R class and basic elements of AndroidManifest.xml file where
the prime system configuration information resides are also discussed. The
main highlight of the chapter is more than one ways of handling events in
Android with are discussed along with suitable examples in each case.
Chapter 3 explores different types of resources available in Android. Basic
steps involved in creating and using string resource, string array resource, style
resource and menu resource both in eclipse and Android Studio are discussed.
Finally
Chapter 4 provides an overview of various pre-defined dialogs available in
Android such as Alert Dialog, Date Picker Dialog,
Time Picker Dialog, Progress Dialog and Characer Picker Dialog which aid in
rapid application development and help in
rendering the application user friendly.
Academic

Evincepub
E Publishing

You might also like