Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
650 views

Android Application Development E-Book

Android A.T.C. Android Application Development Hands-on guide to Android programming. No part of this document may be reproduced, stored in or introduced into a retrieval system. Android ATC company is not responsible for webcasting or any other form of transmission. The inclusion of any link does not imply endorsement of the site or the products contained therein.

Uploaded by

Rron Krasniqi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
650 views

Android Application Development E-Book

Android A.T.C. Android Application Development Hands-on guide to Android programming. No part of this document may be reproduced, stored in or introduced into a retrieval system. Android ATC company is not responsible for webcasting or any other form of transmission. The inclusion of any link does not imply endorsement of the site or the products contained therein.

Uploaded by

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

Android A.T.C.

Android Application
Development
Hands-on guide to Android programming

Android A.T.C. Team

Information in this document, including URL and other Internet Web site references,
is subject to change without notice. Complying with all applicable copyright laws is the
responsibility of the user. Without limiting the rights under copyright, no part of this
document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying,
recording, or otherwise), or for any purpose, without the express written permission of
Android ATC company.
Android ATC company is not responsible for webcasting or any other form of
transmission received from any linked site.
Android ATC company is providing these links to you only as a convenience, and the
inclusion of any link does not imply endorsement of Android ATC of the site or the
products contained therein.
Android ATC company may have patents, patent applications, trademarks, copyrights, or
other intellectual property rights covering subject matter in this document. Except as
expressly provided in any written license agreement from Android ATC company, the
furnishing of this document does not give you any license to these patents,
trademarks, copyrights, or other intellectual property.
This book is available from www.androidatc.com
Copyright Android ATC 2012

Table of Contents
Lesson 1 Hello Android Framework-------------------------------------------------------------- 1
Introduction -----------------------------------------------------------------------------------------------1
Creating an Android Project -----------------------------------------------------------------------------1
Within Eclipse ------------------------------------------------------------------------------------------ 1
From Command line --------------------------------------------------------------------------------- 2
Running Your Application ------------------------------------------------------------------------------ 2
Running you project on the emulator -------------------------------------------------------------- 2
Components of an Android application --------------------------------------------------------------- 6
Application Life-cycle ----------------------------------------------------------------------------------- 7
Modifying created project ------------------------------------------------------------------------------ 8
Change activitys name ------------------------------------------------------------------------------ 8
Lesson 2 Android SDK Tools and Activity Class -------------------------------------------- 10
Android Software Layers ------------------------------------------------------------------------------- 10
Linux kernel ------------------------------------------------------------------------------------------ 10
C/C++ Libraries ------------------------------------------------------------------------------------- 10
Android Runtime ------------------------------------------------------------------------------------ 11
Application Framework ---------------------------------------------------------------------------- 11
Application layer ------------------------------------------------------------------------------------ 11
Android Libraries --------------------------------------------------------------------------------------- 11
The Android Manifest File ----------------------------------------------------------------------------- 12
Structure of the Manifest File ------------------------------------------------------------------------- 13
Android SDK Tools ------------------------------------------------------------------------------------- 13
Activity life-cycle through Java -------------------------------------------------------------------- 15
Create an Activity --------------------------------------------------------------------------------------- 17
Methods to remember ---------------------------------------------------------------------------------- 20
Lesson 3: ListActivity and ListView ------------------------------------------------------------ 21
Introduction --------------------------------------------------------------------------------------------- 21
Views ----------------------------------------------------------------------------------------------------- 21
Using Views ------------------------------------------------------------------------------------------ 22

Android ATC 2012

II

Adding a View to your application ---------------------------------------------------------------- 22


List Views and List Activity ---------------------------------------------------------------------------- 24
Using a ListActivity---------------------------------------------------------------------------------- 24
Adding ListView ------------------------------------------------------------------------------------- 26
Add Event to List Items ----------------------------------------------------------------------------- 28
Summary --------------------------------------------------------------------------------------------- 29
Methods to remember ---------------------------------------------------------------------------------- 29
Lesson 4 Intents and Intent filters ------------------------------------------------------------ 30
Introduction ---------------------------------------------------------------------------------------------30
Intents----------------------------------------------------------------------------------------------------30
Explicit Intents --------------------------------------------------------------------------------------- 30
Implicit Intents --------------------------------------------------------------------------------------- 31
Native Android Actions -------------------------------------------------------------------------------- 31
Data Transfer -------------------------------------------------------------------------------------------- 32
Intent to Call Activities --------------------------------------------------------------------------------- 32
Direct calls -------------------------------------------------------------------------------------------- 32
Sub-activities: Calling Activities for Results ----------------------------------------------------- 33
Register an IntentFilter -------------------------------------------------------------------------------- 34
Methods to remember: --------------------------------------------------------------------------------- 35
Lesson 5: Custom Views --------------------------------------------------------------------------- 36
Introduction --------------------------------------------------------------------------------------------- 36
Different Uses of Customized Views ------------------------------------------------------------------ 36
Modify Existing Views---------------------------------------------------------------------------------- 36
Step by Step ------------------------------------------------------------------------------------------- 36
What is in onDraw() -------------------------------------------------------------------------------- 39
The full picture --------------------------------------------------------------------------------------- 39
Lesson 6: Dialogs and Toasts --------------------------------------------------------------------- 42
Dialogs --------------------------------------------------------------------------------------------------- 42
Dialog sub-classes -------------------------------------------------------------------------------------- 42
Creating dialogs with user-defined layout ------------------------------------------------------- 42
Activities with Dialog Theme -------------------------------------------------------------------------- 47
Toasts ---------------------------------------------------------------------------------------------------- 48
Methods to remember ---------------------------------------------------------------------------------- 51

Android ATC 2012

III

Lesson 7: More UI - Options Menu, Context Menu, and WebView --------------------- 52


Introduction --------------------------------------------------------------------------------------------- 52
Menus ---------------------------------------------------------------------------------------------------- 52
Building a menu from Java code ------------------------------------------------------------------ 52
Building a menu from a resource file ------------------------------------------------------------- 54
Handle Select Events -------------------------------------------------------------------------------- 56
Sub-menus -------------------------------------------------------------------------------------------- 57
Context Menus ------------------------------------------------------------------------------------------ 57
Handling Context Menu Selection ----------------------------------------------------------------- 58
Additional Menu Item options ------------------------------------------------------------------------ 59
Checkboxes and Radio Buttons -------------------------------------------------------------------- 59
Shortcut Keys ----------------------------------------------------------------------------------------- 59
Condensed Titles -------------------------------------------------------------------------------------60
Menu Item Click Listener ---------------------------------------------------------------------------60
Intents -------------------------------------------------------------------------------------------------60
WebView -------------------------------------------------------------------------------------------------60
Methods to remember ---------------------------------------------------------------------------------- 62
Practical Exercise ( 1.5 hr) ----------------------------------------------------------------------------- 62
Lesson 8: Android Storage: Network, File I/O, and SharedPreferences ------------- 63
Android Storage Options ------------------------------------------------------------------------------ 63
Shared Preferences ---------------------------------------------------------------------------------- 63
Internal Storage ------------------------------------------------------------------------------------- 63
SQLite Databases ------------------------------------------------------------------------------------ 63
Network Connection--------------------------------------------------------------------------------- 63
Connecting to the internet ----------------------------------------------------------------------------- 63
File I/O --------------------------------------------------------------------------------------------------- 64
Including files as resources ---------------------------------------------------------------------------- 65
Shared Preferences ------------------------------------------------------------------------------------- 65
Retrieving Shared Preferences ------------------------------------------------------------------------ 66
Save activity state --------------------------------------------------------------------------------------- 66
Lesson 9: Android Storage: SQLite and Content Providers ------------------------------69
Introduction --------------------------------------------------------------------------------------------- 69
SQLite in your application ----------------------------------------------------------------------------- 69
SQLite library ------------------------------------------------------------------------------------------- 69
Android ATC 2012

IV

SQLiteOpenHelper ----------------------------------------------------------------------------------- 69
SQLiteDatabase -------------------------------------------------------------------------------------- 69
Cursors ------------------------------------------------------------------------------------------------ 70
Databases in Android ---------------------------------------------------------------------------------- 70
Native Android Content Providers -------------------------------------------------------------------- 72
Methods to remember ---------------------------------------------------------------------------------- 72
Lesson 10: Android Notifications --------------------------------------------------------------- 73
Introduction --------------------------------------------------------------------------------------------- 73
Creating a notification---------------------------------------------------------------------------------- 73
Notification actions ------------------------------------------------------------------------------------- 73
Example: NotificationManager ------------------------------------------------------------------- 74
Summary------------------------------------------------------------------------------------------------- 77

Android ATC 2012

Lesson1: Hello Android Framework


Introduction
In this lesson you will learn about the Android software development kit (SDK) and its
application framework. All lessons in this book will be using Eclipse IDE in the examples that
access Android SDK tools.
To properly learn from this book, you should have the Android SDK and the Eclipse Android
Development Tools (ADT) plug-in installed.

Creating an Android Project


To create an Android project, you have to create a set of files and a proper structure of folders.
The following steps will help get these files and folder created automatically, before you can start
developing your Android application.

When you install the Android SDK, you will have a set development tools and utilities installed
on your hard disk that will help during your Android development. Most of these tools are
accessible from the Eclipse ADT plug-in through a set of views and buttons (more on this in
lesson 2). Thats why all the Android operations you perform from inside Eclipse, can be
performed from command line. The Eclipse ADT provides a simple and intuitive GUI to access
these commands.

Within Eclipse
To create a project from within Eclipse (preferred method)
1

From the menu bar click on File

Android ATC 2012

New

Android Application Project

2
3

Enter the application name and project name (Can be the same)
Enter the package name. This is a unique name for your application and used by Android
system to differentiate between your applications and others. Make sure the name
follows a proper folder structuring e.g. com.android.atc.lesson1
4 From the Build SDK drop-down list, choose the preferred target for you application.
The list will contain all APIs that you have installed in your machine using the Android
SDK Manager. It means that your code will be conforming to that API. Note that if you
choose a high SDK version, then your application might not work on older devices. Click
Next
5 Choose to build a blank Activity. Click Next.
6 Keep default value as is and click Finish.
Your Android project is now set up with required files and you can start building your
application.

From Command line


The same project setup created by Eclipse can be achieved using command lines:
1

Under a Windows machine, open a command prompt but clicking on start run, type
cmd, then click OK

Change current directory to Android tools directory: <SDK-home>/android-sdk/tools

Execute: android list targets, to get a list of all android platforms installed. Take a note of
the target id.

Execute:
android create project --target <target-id> --name MyFirstApp
--path <path-to-workspace>/MyFirstApp --activity MyFirstActivity --package
com.example.myapp
Replace <target-id> with your SDK version of preference, and <path-to-workspace>
with the location you want to save your project in.

Your Android project is now set up with several default configurations and youre ready to start
Android development.

Running Your Application


You need to run you application frequently during development. To do that, ADT provides a very
useful emulator of Android devices you can use. You do not need a real Android mobile device
for testing, though its possible if you like to.

Running you project on the emulator


Running your project on an emulator involves two steps:
1

Creating an Android virtual device.

Android ATC 2012

Running your project on the emulator.

Creating an Android virtual Device


An Android Virtual Device (AVD) is a configuration for a device emulator that lets you define
actual hardware and software options to be emulated by the Android Emulator.
To create an Android virtual device:
1

Launch the Android Virtual Device Manager:


a In Eclipse, click Android Virtual Device Manager
following dialog shows up:

from the toolbar, and the

The AVD Manager showing few virtual devices.

2
3
4
5

Click New and fill in the details for the AVD. Give it a name, a platform target, an SD
card size, and a skin.
Click Create AVD.
Select the new AVD from the Android Virtual Device Manager and click Start.
The emulator needs few minutes to boot up for the first time, then you can unlock the
screen.

Running your project on the emulator


To run the app from Eclipse, open one of your project's files and click Run from the toolbar.
Eclipse installs the app a compatible AVD (the one created in previous section) and starts it. If
you check the console view under Eclipse, you should an output similar to the following while
installing the application to the project:

Android ATC 2012

[2012-08-08 15:37:23 - Lesson1] -----------------------------[2012-08-08 15:37:23 - Lesson1] Android Launch!


[2012-08-08 15:37:23 - Lesson1] adb is running normally.
[2012-08-08 15:37:23 - Lesson1] Performing com.android.atc.android.Lesson1Activity activity launch
[2012-08-08 15:37:23 - Lesson1] Automatic Target Mode: launching new emulator with compatible
AVD 'Android_ATC_AVD'
[2012-08-08 15:37:23 - Lesson1] Launching a new emulator with Virtual Device 'Android_ATC_AVD'
[2012-08-08 15:37:27 - Lesson1] New emulator found: emulator-5554
[2012-08-08 15:37:27 - Lesson1] Waiting for HOME ('android.process.acore') to be launched...
[2012-08-08 15:38:16 - Lesson1] HOME is up on device 'emulator-5554'
[2012-08-08 15:38:16 - Lesson1] Uploading Lesson1.apk onto device 'emulator-5554'
[2012-08-08 15:38:16 - Lesson1] Installing Lesson1.apk...
[2012-08-08 15:38:33 - Lesson1] Success!
[2012-08-08 15:38:33 - Lesson1] Starting activity com.android.atc.android.Lesson1Activity on device
emulator-5554
[2012-08-08 15:38:35 - Lesson1] ActivityManager: Starting: Intent { act=android.intent.action.MAIN
cat=[android.intent.category.LAUNCHER] cmp=com.android.atc.android/.Lesson1Activity }

Your Android application is installed on an emulator and you can now starting development.
You will notice that the emulator home screen will be the lock screen. Unlock it to see your
projects screen:

Android ATC 2012

Default screen of newly created project

The emulators window is not re-sizable. Sometimes, you will be developing on


a laptop or any pc with a small screen that some parts of the emulator would be
out of boundaries. To resolve this, you can change the emulators size following
these steps:
1. Click on the arrow next to run button
2.

3. choose Run Configuration....


4. Under the Target tab of you project, fill in the the following command in
field Additional Emulator Command Line Option: -scale 0.75
5. Click Apply, then Run
The emulator window will be 75% of its original size.

Android ATC 2012

Components of an Android application


The following are the major component that provide the building blocks for any Android
application and act as a possible entry point for your application:
1. Activities
This is your applications user interface. Every screen in an application extends the
Activity class. Activities use Views to create graphical user interfaces interact with the
user.
2. Services
A service is the invisible part of your application. They run invisibly updating data
sources and visible Activities. Services are used to perform continuous processing even
when an applications Activities arent active or visible.
3. Content Providers
They are a data store that is exposed for sharing. Content Providers manage and share
application databases. They are the preferred way of sharing data across different
applications; i.e. you can configure your own Content Providers to permit access from
other applications. Android provides several native Content Providers that expose useful
databases like contacts and call logs information.
4. Broadcast Receivers
They consume messages broad-casted by Intents. When a broadcast receiver is added to
your application, it means your application can listen for broadcast Intents that match
specific filter criteria.

The following are other examples of some of Android Java objects you will see frequently in this
book:
1. Views
Views are objects that know how to draw itself to the screen. Each activity is made up of
a set of views grouped together within a layout. View is the parent class of all Activity
widgets.
2. Intents
These are objects used to send message across the whole Android system. They are used
to broadcast messages, start an Activity, or start a Service, including an intention to have
an action performed. Its the systems duty to interpret the message and determine the
target(s) that will perform any actions as appropriate.
3. Notifications
They can be used in an application to alert users to certain events without having a
visible activity. Notifications do not steal focus or interrupt users current interaction
with an activity. They are preferably used to get a users attention from within a service.
For example, when a service finishes downloading a file from the Internet, it can alert the
user by a notification that can make sound, show dialog messages, vibrate....etc.

Android ATC 2012

Application Life-cycle
Contrary to traditional applications you build, Android applications life cycle is controlled by
the Android framework itself. Its Android that runs and shuts down correctly the applications
when it is needed. Android applications are always listening to changes in its state and respond
accordingly till it reaches proper termination. Each Android application runs its own process
and process management is handled exclusively at run time. You will learn later about the
handling of life cycle event through Java call-back methods.
Android actively manages its resources, doing whatever it takes to ensure that the device
remains active. To achieve this, Android will kill applications without a warning if necessary to
free resources for applications of higher priority.

To determine which processes should be killed when low on memory, Android classifies each application
into an importance hierarchy based type of components the application is made of and the state of those
components.

Type of Android processes and their priorities


Foreground (Active) processes
Those are applications with components currently interacting with the user. These are
the processes Android is trying to keep responsive by reclaiming resources. There are
generally very few of these processes, and they will be killed only as a last resort.

Visible process
Visible, but inactive processes are those hosting visible Activities. As the name
suggests, visible Activities are visible, but they arent in the foreground or responding to
user events. This happens when an Activity is only partially obscured (by a non-fullscreen or transparent Activity). There are generally very few visible processes, and theyll
only be killed in extreme circumstances to allow active processes to continue.

Android ATC 2012

Services
Processes hosting Services that have been started. Services support ongoing processing
that should continue without a visible interface. Because Services dont interact directly
with the user, they receive a slightly lower priority than visible Activities. They are still
considered to be foreground processes and wont be killed unless resources are needed
for active or visible processes.

Background process
Processes hosting Activities that arent visible and that dont have any Services that have
been started are considered background processes. There will generally be a large
number of background processes that Android will kill using a last-seen-first-killed
pattern to obtain resources for foreground processes.

Empty process
To improve overall system performance, Android often retains applications in memory
after they have reached the end of their lifetimes. Android maintains this cache to
improve the start-up time of applications when theyre re-launched. These processes are
routinely killed as required.

Modifying created project


At the beginning of this lesson, we created a project which contains - by default - a single screen
(Activity) showing a Hello World! message. In this exercise, well try to get familiar with the
android project structure by doing two minor changes:
1
2

Changing the main activitys name that shows up in the top bar
Changing the Hello World! message.

Change activitys name


To change the Activity name which shows up in the top bar of the screen and the Hello World!
message, follow these steps:
1
2
3
4
5
6
7

Under Package explorer in the left pane, expand the res folder under project Lesson1.
Expand values folder
Double click on strings.xml file
Make sure the Resources tab is opened, then clicked on element title_main_activity.
On the right side of the screen, under field Value*, replace MainActivity with Lesson
1
Click element hello_world, then under field Value*, replace Hello World! with Hello
World from Android A.T.C.!
Save changes - either by pressing CTRL+S or by clicking on the save button in Eclipse.

Android ATC 2012

Run the project and youll see the changes on the main screen of your application:

Activity after modification

Android ATC 2012

Lesson 2
Android SDK Tools and Activity Class
Android Software Layers
The Android system is made up of several layers as shown in the figure below.

Linux kernel
Android relies on a Linux kernel for core system services such as security, memory management,
process management, network stack, and hardware drivers. The kernel also acts as an
abstraction layer between the hardware and the rest of the software stack. Linux is a proven
driver model and efficient in resource management.

C/C++ Libraries
On top of the Linux kernel comes a set of native libraries written in C/C++, which are
responsible for stable performance of various components. They manage the access for different
processes to compose 2D and 3D graphic layers. They are also responsible for media framework
Android ATC 2012

10

processing; i.e. playback and recording support for all the major media and static image files - in
addition to supporting fonts, data storage, and web browsers.

Android Runtime
Next to the C/C++ libraries lies the Android Runtime, where the main component Dalvik
Virtual Machine (DVM) is located. It was designed based on Java Virtual Machine specifically
for Android running in limited environment, where the limited battery, CPU, memory and data
storage are the main issues. Instead of .jar file that are read by JVM, the DVM read .dx files.
These byte-code optimized files that are more efficient to run on small processes.
Android runtime contains core libraries that are written in Java language and contains of the
collection classes, the utilities, IO and other tools.

Application Framework
The Application Framework is written in Java language. It is a collection of Java libraries that all
Android applications use, whether native Android applications like dialer or any other
application any Android developer. It has several components, for example the Activity Manager
manages the life cycle of the applications, the Package Manager keeps track of the applications,
which are installed in the device, the Telephony Manager contains of a set of API necessary for
calling applications notification manager is used to customize display alerts and other functions.

Application layer
This is the upper most layer of the Android Architecture which contains all the applications used
by the end user. All application that you build lies in this layer and they are all written using the
Java programming language.

Android Libraries
Android offers a set of Java APIs for developing your applications. The following is a noncomplete list of the main libraries provided by Android SDK. All Android devices must provide
support for these libraries:
android.view
This library provides the main classes for Android graphical user interfaces and for handling
users interaction with the UI. The View class -part of this package- is the most important UI
class which other screen components inherent from.
android.widget
The widget package contains GUI elements to use on your Applications screen. This package
derives from the view package and contains built-in views ready to be used on a screen.
android.util
This is the main utility package which includes special classes like string utilities formatters and
XML parsers.
Android ATC 2012

11

android.database
It provides the API to access low-level interactions with Android databases and handling
cursors.
android.content
Provides classes to manage data access. These classes are mainly used with resources, content
providers, and packages. Context class is part of this library.
android.app
Provides access for high-level components of the application model. For example, Activity and
Service classes - basic classes for all Android applications - are part of this package.
android.provider
This library provides easier access to the basic Content Providers, like the contacts and calendar
databases.
android.telephony
Telephony package gives the ability to monitor basic phone information, like the phone state,
network connectivity, and SMS messages.
android.webkit
Provides classes to allow your application to browse the web. The main class in this library used
by developers is WebView.
In addition to set of advanced Android libraries like android.location, android.media,
android.opengl, android.hardware, android.bluetooth, ...etc.

The Android Manifest File


The Android manifest is the most important file that every application must contain in its root
directory and should be named exactly AndroidManifest.xml. It is - as the name suggests an XML file that provides essential information about the application to the Android system,
information the system must have before it can run any of the application's code. The following
are some of the information the manifest contains:

The Java package names of the application, which is a unique identifier for the
application.

A detailed description of the applications components, i.e. the activities, services,


broadcast receivers, and content providers that the application is composed of. Each of
these components has a special XML tag syntax.

It declares which permissions the application must have in order to access protected
parts of the API.

Android ATC 2012

12

It declares the minimum level of the Android API that the application requires. This value
determines whether your application is supported on a certain devices Android OS
version or not.

Structure of the Manifest File


The image below is a sample of a manifest file that shows the structure and every element that
it can contain.

Android SDK Tools


Android SDK installed locally on your disk, comes with a set of tools that are very helpful for
your development work. To check all the tools and programs that comes with the SDK browse to
the following folder: <SDK>/android-sdk/platform-tools and <SDK>/androidsdk/tools where SDK is the installation folder of your SDK. The following is a list of the most
important Android SDK tools you might find helpful during your application development
1

DDMS: Stands for Dalvik Debug Monitor Server, its a debugging tool which provides
screen capture on the device, thread and heap information on the device, logcat, process,
and radio state information, incoming call and SMS spoofing, location data spoofing, and
more.

Android ATC 2012

13

To run DDMS from Eclipse: Click Window > Open Perspective > Other... > DDMS.

HierarchyViewer: allows you to debug and optimize your user interface. It provides a
visual representation of the layout's View hierarchy (the Layout View) and a magnified
inspector of the display

Android ATC 2012

14

ADB: Android Debug Bridge (adb) is a command line tool that lets you communicate
with an emulator or connected Android-powered phone. It is a client-server program
that includes: a client, which runs on your development machine, a server, which runs as
a background process on your development machine, and a daemon, which runs as a
background process on each emulator or device instance.

Logcat: A mechanism for collecting and viewing system debug output. Logs from
various applications and portions of the system are collected, which then can be viewed
and filtered by the logcat command. You can use logcat from an ADB shell to view
the log messages using command adb logcat, or more preferrably, use DDMS from
within Eclipse to see your application logs in the logcat view

To log a message in your application and make it viewable through logcat, use the
following syntanx:
Log.i("Application Tag", "This is the logged message);

Traceview: This is a graphical viewer for execution data saved by your application. It
help you debug your application and profile its performance. Traceview is located under
tools/ SDK directory.

Activity life-cycle through Java


Activity is the base class for every Android application component that contains graphical user
interface. Every application you open and you interact with is an extension of class Activity.
In Lesson 1, you have seen a description of the an Androids activity life-cycle. Every state of this
cycle is represented and provided to application developer with the use of Java call backs. These
Android ATC 2012

15

are functions that are called by the Android system whenever an event occurs. For example,
when you launch an Android application, the moment the Android system starts loading the
main activity of that application, it sends the callback onCreate(). In your Java code you can
override that method and add your own Java code to be executed by the system. In fact, Android
SDK provides a callback method for each event in an activity life-cycle. The following is skeleton
of a Java class which extends Activity and overrides its life-cycle events.
import android.app.Activity;
import android.os.Bundle;
public class MyActivity extends Activity {
// Called at the start of the full lifetime.
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Initialize activity.
}
// Called after onCreate has finished, use to restore UI state
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
}
// Called before subsequent visible lifetimes
// for an activity process.
@Override
public void onRestart(){
super.onRestart();
// Load changes knowing that the activity has already
// been visible within this process.
}
// Called at the start of the visible lifetime.
@Override
public void onStart(){
super.onStart();
// Apply any required UI change now that the Activity is visible.
}
// Called at the start of the active lifetime.
@Override
public void onResume(){
super.onResume();
// Resume any paused UI updates, threads, or processes required
// by the activity but suspended when it was inactive.
}
// Called to save UI state changes at the
// end of the active lifecycle.
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
super.onSaveInstanceState(savedInstanceState);
}
// Called at the end of the active lifetime.
@Override

Android ATC 2012

16

public void onPause(){


// Suspend UI updates, threads, or CPU intensive processes
// that dont need to be updated when the Activity isnt
// the active foreground activity.
super.onPause();
}
// Called at the end of the visible lifetime.
@Override
public void onStop(){
// Suspend remaining UI updates, threads, or processing
// that arent required when the Activity isnt visible.
// Persist all edits or state changes
// as after this call the process is likely to be killed.
super.onStop();
}
// Called at the end of the full lifetime.
@Override
public void onDestroy(){
// Clean up any resources including ending threads,
// closing database connections etc.
super.onDestroy();
}
}

Create an Activity
To add an activity to the project that we created in Lesson 1, you should follow these steps:
1

Create a Java class that extends Activity


public class MyActivity extends Activity

Override the onCreate() event:


public void onCreate(Bundle savedInstanceState)

Create a layout resource


Resource files are saved under the res folder of your application. The following image

Android ATC 2012

17

shows the default folder structure created by ADT when you create a project:

Resource files are files that contain raw data that can be accessed and used by your Java
code. Each Activity must have a layout. You can specify the components of that layout in
an XML resource file saved under res/layout. To create a layout:

Android ATC 2012

18

Right click on res/layout folder, then choose News Android XML File

Choose Layout for the Resource Type, then type in my_layout as the name of
the file.

Click on Finish.

Add the Activity to your AndroidManifest.xml file. The file is located in the root
folder of your application. Every activity in an application that a user would interact with
must be included in the manifest file. By doing this, the Android system would be
notified of the activitys presence. If you omit this step, then your Java and layout files
would simply not exist according to the system even if included in your application
package. To add the activity follow these steps:
a

Double click on AndroidManifest.xml

In the Manifest editor, click on the application tab below:

Android ATC 2012

19

Click on Add... then choose Activity.

In the right pane, fill in the Name* field, which is the Java class name you
created in step 1. Click on Browse..., then choose the Java class.

Save your work by type Ctrl+s.

After you add required files, you have to tell the Java Activity class created in step 1 to
use the layout file created in step 3. Do so by calling setContentView() method inside
onCreate() method. setContentView(R.layout.my_layout) Where my_layout is
the name of the XML layout file under res/layout/.

Methods to remember

onCreate()
setContentView()
findViewById()

Android ATC 2012

20

Lesson 3: ListActivity and ListView


Introduction
An Activity is a crucial component of your Android application. It is actually an obligatory
component if you want the user to interact with your application. If you have used an Androidpowered device enough, you must have used seen a list views or list activity. A list view is a
compound type of View that displays a set of views vertically. A ListActivity is a sub type of
Activity that facilitates building list views.

This lesson will introduce views in general and focus on list components and other concepts
revolving around lists.

Views
The View is a Java class that represents the basic building block for user interface components.
It is the parent class of all other interactive UI components (widgets) of your application like
buttons, text fields, labels...etc.. It occupies a rectangular area on the screen and is responsible
for drawing and event handling. The ViewGroup subclass is the base class for layouts, which
are invisible containers that hold other Views (or other ViewGroups) and define their layout
properties.
Android ATC 2012

21

Using Views
All of the views in a window are arranged in a single tree. You can add views either from code or
by specifying a seet of views in XML layout files. There are many specialized subclasses of views
that act as controls or are capable of displaying text, images, or other content.
Once you have created your views, you typically might need to perform some of the following:

Set properties: for example setting the text of a TextView. The available properties
and the methods that set them will vary among the different subclasses of views. Note
that properties that are known at build time can be set in the XML layout files.
Set focus: The framework will handled moving focus in response to user input. To force
focus to a specific view, call requestFocus().
Set up listeners: Views allows you to set listeners that will be notified when something
event happens to the view. For example, some views like the Button will let you set a
listener to be notified when it is clicked. You can register such a listener using
setOnClickListener(OnClickListener).
Set visibility: You can hide or show views using setVisibility(int).

Adding a View to your application


To add a view to an activity in your application you can do so in two way, either purely through
Java code, or by adding it in a XML layout file. The latter is always the recommended method,
and can be used followed these steps:
1

Create a new project, then open the default layout under res/layout called
main_activity.xml

Android ATC 2012

22

The visual layout editor opens in the right pane of Eclipse

To add a button to the layout, drag the Button component from under Form Widgets
in the left pane, to inside the activity in the right.

Save your work.

Run your application in the emulator to view your added button.

Android ATC 2012

23

List Views and List Activity


You can manipulate list views in your application in one of two ways:

Using ListActivity - a sub type of Activity that is made up of a single List view only.

Adding a list view component to your own XML layout file.

If you are planning to create an activity that contains a list view only, then the first method is
recommended for simplicity. However, if List view is only one of many components in your
activity then you have to use the second method.

Using a ListActivity
ListActivity is a sub-class of Activity that features a ListView as a the primary UI. The following
steps describe how to view a list of strings using ListActivity.
1

After you create a project, add a Java class that extends ListActivity, the same way you
added an Activity in previously. The code should be similar to this:

public class MyListActivity extends ListActivity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}

Android ATC 2012

24

Create a String array of element you want to display. Lets assume we want to display a
list of Android version names:

static final String[] ANDROID_OS = new String[] {Cupcake, Donut, "Eclaire, Froyo,
GingerBread", HoneyComb, "Ice Cream Sandwich", "JellyBean" };

Link your array of raw data to the list view using an Adapter:

setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, ANDROID_OS));

Save your work and run your application.

Putting the code in the previous steps together will provide the following following simple class
which produces the list view in the image above:
import
import
import
import

android.app.ListActivity;
android.os.Bundle;
android.widget.ArrayAdapter;
android.widget.ListView;

public class MyListActivity extends ListActivity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String[] ANDROID_OS = new String[] {"Cupcake", "Donut", "Eclaire", "Froyo",
"GingerBread", "HoneyComb", "Ice Cream Sandwich", "JellyBean" };

setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
ANDROID_OS));

Android ATC 2012

25

Adapters are Java classes used in Android SDK to bind your presentation layer
to data sources. There are different sub-classes of Adatper depending on the
type of data to be bound, like ArrayAdapter, CursorAdapter...etc.

Adding ListView
In the previous section, you have seen how to populate a ListView indirectly through the usage
of ListActivity. In this section, we will add a ListView to a layout of a Java class that extends
Activity (rather than ListActivity).
1

Layout file
Add a layout file for the list item only under res/layout. This resource file only
represents the layout of each item in the ListView. Call it list_os.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="20sp" >
</TextView>

Open the res/layout/main_activity.xml, then add List View component from under
Composite category of the palette pane.

Android ATC 2012

26

Set the id property of the ListView to the preferred name. To change a property in a
widget in the layout visual editor, click on it, then a properties view will show up in
Eclipse. Look for the id property field, then change to @+id/listViewOS. ( by default the
value will be @+id/listView1)

Create a Java class that extends Activity, then get a reference to the ListView widget you
have just added in step 3:
public class ListFruitActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get a reference to the list view widget
ListView listVieww = (ListView) getElemenById(R.id.listViewOS);
}

Create a String array of Android OS version names you want to display:


static final String[] ANDROID_OS = new String[] {Cupcake, Donut, "Eclaire, Froyo,
GingerBread", HoneyComb, "Ice Cream Sandwich", "JellyBean" };

Android ATC 2012

27

Link your array of raw data to the list view variable you created in step 4 using an
Adapter:
listView.setAdapter(new ArrayAdapter<String>(this,R.layout.list_os, ANDROID_OS));

Now you can run your application and view similar list as the previous section. However in this
method you can add as much widgets as you want, and can get more control over the list
properties. The final Java class will look like this:

package com.android.atc.lesson3;
import
import
import
import

android.app.Activity;
android.os.Bundle;
android.widget.ArrayAdapter;
android.widget.ListView;

public class ActivityWithListView extends Activity {


/** Called when the activity is first created. */
ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
static final String[] ANDROID_OS = new String[] {Cupcake,
Donut, "Eclaire, Froyo, GingerBread", HoneyComb, "Ice Cream
Sandwich", "JellyBean"};
ArrayAdapter<String> aa
= new ArrayAdapter<String>(this,R.layout.list_os, ANDROID_OS);
listView = (ListView) findViewById(R.id.listViewOS);
lv.setAdapter(aa);
}
}

Add Event to List Items


Now that you can view display items in a list, you can make every item in the list click-able by
attaching event listener to the list view. To do so, add the following code in your onCreate()
method, right after you set the lists adapter:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, print out the text inside an item
System.out.println(((TextView) view).getText())
}
});

Android ATC 2012

28

Summary
The following is a summary of the steps you should follow to populate a ListView:
1

Create a ListView instance.


ListView listView;

Initialize the instance


getListView() OR
findViewById(R.id.listViewOS);

Create an Adapater. e.g. ArrayAdapter


ArrayAdapter arrayAdapter = new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, elementsArray)

Attach the adapter to the ListView using:


setListAdapter(arrayAdapter) OR
listView.setAdapter(arrayAdapter)

Now that you can view the items in a list, you can make every item in the list clickable
using:
setOnItemClickListener(new OnItemClickListener(){});

Methods to remember

getListView()

setListAdapter( ArrayAdapter aa )

ArrayAdapter(Context, layout, String[])

setOnItemClickListener( OnItemClickListener oicl)

Android ATC 2012

29

Lesson 4: Intents and Intent filters


Introduction
The Android system uses messages to communicate between its components. These message
inform the system what the issuing component wants to do i.e. its intent. Android SDK provides
the developer this ability through the Intent class.
In other words, intents are a simple message-passing framework. that can broadcast messages
system-wide or to a target Activity or Service, stating an intention to perform an action.
Intents are also used to transfer data between different component by attaching it to the
message. This lesson will discuss different types of intents and how to use them.

Intents
Intents are used for interaction between different android components. They glues separate
components into an interconnected system. When a button click starts an activity i.e. brings a
new activity to the foreground and the current activity goes to the background, it basically sends
the Android system a message telling it of its intention start an activity. From the Android
system perspective, there is two types of intents: explicit and implicit.

Explicit Intents
Explicit Intents specify which component it wants to start. They basically tell the system where
from the message is issued and to which component i.e. which activity or service. It does so by
specifying explicitly the name of the class to load as a parameter to the Intent constructor.
The following code sample is taken from inside an activity. It create an Instance of the Intent
class, and starts another activity:
Intent intent = new Intent(this, ActivityTwo.class);
startActivity(intent);
In these lines, the Intent constructor specifies explicitly which activity is intends to start, by providing its
name ActivityTwo.class. You can think of the two parameter of the constructor, as the source and
destination of the message, where this refers to the current activity.

Android ATC 2012

30

Briefly, explicit Intents are mainly used to start activities i.e. open a different application screen in your
application, or a service.

Implicit Intents
Rather than specifying the destination class name, implicit intent only specifies an Action, and
the underlying Android system will translate that action and starts the components that can deal
with it. The following two examples show two implicit intents
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.Androidatc.com"));
startActivity(intent);

This intent sends a message with two pieces of information. The action it should perform
(ACTION_VIEW) and the data it wants the receiver to process i.e. the url. The Android system
receives the message and looks for activities that can process this action and data.
ACTION_VIEW,

Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(tel:555-1234));


startActivity(intent);

This implicit intent sends the ACTION_DIAL with a data URI made of a telephone number. The
Android system will launch its phone dialer and add the phone number supplied to the dialer to
be ready for dialing.

Native Android Actions


In the previous section, you saw two examples of native Android actions, ACTION_VIEW and
ACTION_DIAL. The following is a list of some of the native actions available as static string
constants in the Intent class. You can use them when creating implicit Intents to start Activities.
ACTION_ANSWER Opens an Activity that handles incoming calls. Currently this is
handled by the native phone dialer.
ACTION_DELETE Starts an Activity that lets you delete the entry currently stored at
the data URI location.
ACTION_DIAL Brings up a dialer application with the number to dial prepopulated
from the data URI. By default, this action is handled by the native Android dialer.
ACTION_EDIT Requests an Activity that can edit the data at the URI.
ACTION_PICK Launches a sub-Activity that lets you pick an item from the URI data.
When closed, it should return a URI to the item that was picked.
ACTION_SEARCH Launches the UI for performing a search. Supply the search term
as a string in the Intents extras using the SearchManager.QUERY key.
ACTION_SEND Launches an Activity that sends the specified data (the recipient needs
to be selected by the resolved Activity). Use setType to set the Intents type as the
transmitted datas mime type. The data itself should be stored as an extra using the key
EXTRA_TEXT or EXTRA_STREAM depending on the type.
Android ATC 2012

31

ACTION_VIEW is most common generic action. It asks that the data supplied in the
Intents URI be viewed in the most reasonable manner. Different components will
handle this action depending on the URI schema of the data supplied.
ACTION_WEB_SEARCH Opens an activity that performs a Web search based on the
text supplied in the data URI.

Data Transfer
It is very likely that you will need to transfer some data to the activity you want to start through
an Intent. Android SDK provides this ability by using extras. You can attach data to your intent
by using Intents method putExtra() in the calling activity and method getExtra() in the
called activity. Suppose you want to send a string from ActivityOne to ActivityTwo when it
starts. First you put the string as extra in the intent from ActivityOne.
Intent intent = new Intent(this, ActivityTwo.class);
intent.putExtra(Intent.EXTRA_TEXT, "News for you!");

Notice that putExtra() takes two parameters: the first is a String constant that acts as a key, and
the second is the string data you want to send. Extras in intents work as key-value pairs, where
the keys serve as a unique identifier of the string sent.
Then, on the receiving side, you read the extra using getExtra().
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
// Get data via the key
String value1 = extras.getString(Intent.EXTRA_TEXT);
if (value1 != null) {
// Do something with the data
}

Now variable value1 should be equal to string News for you! sent by ActivityOne.

Intent to Call Activities


When an activity is started by an intent, there is two types of ways to call that activity: Direct
calls or sub-activity calls.

Direct calls
The examples on intents you have seen so far brings an activity to the foreground, using
startActivity() method.
When this method is used, the activity started is independent and the calling activity is not
expecting and data returned from it. startActivity(Intent) is available in every Activity object.
Android ATC 2012

32

Sub-activities: Calling Activities for Results


Sometimes you want to start an activity only get a result from it and return to the current
activity. For example, suppose you want to ask the user to choose a value from a list in another
activity. In this case, you can call a sub-activities, i.e. an activity that is supposed to return a
result.
To call ActivityTwo for a result from ActivityOne, you have send an intent using method
startActivityForResult():

public void onClick(View view) {


Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");
// Set the request code to any code you like, you can identify the
// callback via this code
startActivityForResult(i, REQUEST_CODE);
}

Notice that the second parameter of startActivityForResult() is an integer constant. This acts as
a unique id for the calling intent.

Still in ActivityOne, you have to override the callback method onActivityResult()

@Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case SHOW_SUBACTIVITY:
if (resultCode == Activity.RESULT_OK)
{
Bundle resultData = data.getExtras();
Log.i("Text",resultData.getString("TextReturned"));
}
break;
}
}

Android ATC 2012

33

In ActivityTwo, you return results by overriding method finish() and inside it use method
setResult(). Android system will then return a call-back to method onActivityResult() in
ActivityOne.
@Override
public void finish() {
// Prepare data intent
Intent data = new Intent();
data.putExtra("TextReturned", This string is sent from
ActivityTwo);
// Activity finished ok, return the data
setResult(RESULT_OK, data);
super.finish();
}

Register an IntentFilter
When an implicit intent is sent, the Android system tries to match that intents action and data
with all activities that can process them. This process is simply a filtration of all activities
registered in Android to receive implicit intents. For example, when you execute the following
statement:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.AndroidATC.com"));

You are implicitly telling Android to look up for all activities that process the Uri which starts
with http:// and expects ACTION_VIEW. By default, every Android system has a default
browser with can process this intent. That is why, executing that line of code will bring up the
web browser.
You can tell Android system to register one of your application activities for certain action and
data, so that it will be launched whenever an implicit intent that matches them is called.
To make one of your activities respond to an implicit intent, follow these steps:
1

Modify Manifest file


a Add <intent-filter> under the <activity> of the activity you want to register.
b Add <action>, <category> and <data> under intent-filter tag

<activity android:name="MyListActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW"></action>
<category android:name="android.intent.category.BROWSABLE"></category>
<category android:name="android.intent.category.DEFAULT"></category>
<data android:scheme="http"></data>
</intent-filter>
Android ATC 2012

34

</activity>

In your activity (MyListActivity) make a call to getIntent(). This will return an instance
of the intent, and allows you to get the intents data for processing.

Intent intent = getIntent();


if(intent.getAction().compareTo(Intent.ACTION_VIEW) == 0)
{
Uri data = intent.getData();
getListView().setFooterDividersEnabled(true);
Toast.makeText(this, data.toString(), Toast.LENGTH_LONG).show();
Log.v("log", intent.getAction());
Log.v("log", Intent.ACTION_VIEW);
}

From another activity, make the implicit intent call.


Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.androidatc.com"));

Now, Android will look up for all activities that match this implicit intent. Since, it already has
the browser application as a match, as well as your registered activity, Android will show up
these two applications in a list, and you have to choose which one to open the intent with.

Methods to remember:

startActivity();
startActivityForResult()
intent.putExtra(String Key, String Value)
bundle.getExtra()
finish()
intent.getExtra()
intent.getAction()
intent.getData()

Android ATC 2012

35

Lesson 5: Custom Views


Introduction
You have seen in previous lessons many Views that comes with the Android framework. These
are only a subset of a big number of View classes that are provides for use interactions - also
called widgets. Each of these views has a default behavior and user interface. However,
sometimes, your application might require a slightly different views that are not included in the
built-in views. This lessons shows you how to create your own customized views that can be
reusable.

Different Uses of Customized Views


With the ability to create your own customized views, the Android framework provides three
different types of customizations:
1

Modify existing views: You can create a different theme and/or behavior of an existing
view provided by Android framework. For example, you can change the default
appearance of the TextView, by drawing a different text and background colors; or you
can change the default behavior of the TextView by adding a left-to-right swipe
functionality for a TextView.
Compound Views: Combine a group of views into a single view. For example, you
might need to create a single view that contains two text views - one as a title of an article
with large font and one below it as a subtitle with smaller font. Then you can use this view
in a ListView of stories.
New views: Create a totally new view that resembles real world object; like a compass
view or a volume knob.

Modify Existing Views


If you need a view similar to a built-in view, then the simplest way is to modify an already builtin view in the Android framework. If there is a component that is already very similar to what
you want, you can simply extend that component and override the behavior and appearance that
you want to change.

When you extend Android View class, you are basically creating a totally customized view.
However, by extending a built-in view (a view that itself extends from the View class) you can
use the already built-in behavior and appearance if it matches what you need and modify the
part that doesnt.

Step by Step
Android ATC 2012

36

The following section shows you how to modify Android TextView to suite your needs. We will
call the view MyTextView.
Here are the steps to create MyTextView:
1

Create a new Java class that extends TextView. It extends TextView, which is the View
we have chosen to customize in this case. When we are finished, the new class will be able
to substitute for a normal TextView view.
public static class MyTextView extends TextView {

Create Constructors
As always, the super is called first. Furthermore, this is not a default constructor, but a
parameterized one. The TextView is created with these parameters when it is inflated
from an XML layout file, thus, our constructor needs to both take them and pass them to
the superclass constructor as well.
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
...
}

Override Methods
To implement a custom view, you should usually override some of the standard methods
that the framework calls on all views. But you can just override
onDraw(android.graphics.Canvas). In this example, we want to change the appearance of
TextView, so we only need to override onDraw() to make our own drawing and
appearance changes. Later in this lesson, we will see how and what to draw in this
method.
@Override
protected void onDraw(Canvas canvas) {

super.draw(canvas);
}

Android ATC 2012

37

The super.onDraw() method is called before the method ends. The superclass method
should be invoked, but in this case, we do it at the end after we have made the
appearance changes we want to include.
4

Use the Custom Component


We now have our custom view. You now need to use it in your application. You can do so
using a layout resource. Create a layout under res/layout and call it
my_text_view.xml. This layout is made up of a single MyTextView item.
<?xml version="1.0" encoding="utf-8"?>
<com.androidatc.views.MyTextView
android:text="MyTextView" android:id="@+id/MyTextView1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical"
android:textColor="@color/notepad_text">
</com.androidatc.views.MyTextView>

The attributes and parameters in the definition of the layout are the ones passed into the
custom component constructor, and then passed through to the TextView constructor, so
they are the same parameters that you would use for a TextView view.
Once you save your customized view Java class you created in step 1, it will
become a widget and appear in the layout editor in Eclipse. You can check it
when you edit you layout. It should appear under section Custom & Library
Views. Click on refresh if it doesnt show up.

Android ATC 2012

38

You are done. All you need to do is to use the customize text view in an Activity. Either
you can use setContentView(R.layout.my_text_view) of an activity, or use the
MyTextView in a ListView where every item in the list contains a MyTextView.

A more sophisticated component can override more handler methods (the ones starting with
on...), substantially customizing its properties and behavior. You can use your imagination to
customize your component the way you want.

What is in onDraw()
The most important step in changing the appearance of a custom view is to override the
onDraw() method which take a Canvas object as a parameter and used to draw itself. The
Canvas class contains several methods to help you draw text, lines, bitmaps...etc. You can use
these methods in onDraw() to customize your view. However, you need to create an instance of
object Paint before you can draw.
Classes Canvas and Paint are two parts of the android.graphics library:
Canvas: defines what shapes that you can draw on the screen
Paint: defines the how you draw on screen using color, style, font, ...etc. of each shape.
For example, to draw a line in our MyTextView class, we must created a Paint object and use as
a parameter to a canvas method call in our onDraw() method.
public void onDraw(Canvas canvas){

Paint linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);


linePaint.setColor(myResources.getColor(Color.BLUE));
canvas.drawLine(0, 0, getMeasuredHeight(), 0, linePaint);

canvas.save();
// Use the TextView to render the text.
super.onDraw(canvas);
...
}

The full picture


The following are the contents of the files we have created in the previous sections of this lesson:
MyTextView.java
package com.androidatc.lesson5.view;
import
import
import
import
import
import

android.content.Context;
android.graphics.Canvas;
android.graphics.Color;
android.graphics.Paint;
android.util.AttributeSet;
android.widget.TextView;

Android ATC 2012

39

public class MyTextView extends TextView {


private Paint linePaint;
public MyTextView(Context context, AttributeSet attrs, int defStyle)
{

super(context, attrs, defStyle);


init();

}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
public void init(){
// Create the paint brushes we will use in the onDraw method.
linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
linePaint.setColor(Color.BLUE);
}
@Override
public void onDraw(Canvas canvas){
canvas.drawLine(0, 0, getMeasuredHeight(), 0, linePaint);
canvas.drawLine(0, getMeasuredHeight(), getMeasuredWidth(),
getMeasuredHeight(),linePaint);

canvas.save();
super.onDraw(canvas);
canvas.restore();

my_text_view.xml
This is saved under res/layout
<?xml version="1.0" encoding="utf-8"?>
<com.androidatc.lesson5.view.MyTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MyTextView" />

Android ATC 2012

40

my_text_view_list.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" >
<ListView
android:id="@+id/my_text_view_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

MyTextViewActivity.java

package com.androidatc.lesson5.activity;
import java.util.ArrayList;
import
import
import
import

android.app.Activity;
android.os.Bundle;
android.widget.ArrayAdapter;
android.widget.ListView;

import com.androidatc.lesson5.notepad.R;
public class MyTextViewActivity extends Activity {
ListView myTextViewListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_text_view_list);
final ArrayList<String> items = new ArrayList<String>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
final ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
R.layout.my_text_view, items);
myTextViewListView = (ListView) findViewById(R.id.my_text_view_list);
myTextViewListView.setAdapter(aa);
}
}

Android ATC 2012

41

Lesson 6: Dialogs and Toasts


Dialogs
Dialogs are small windows that appear in front of an activity. They occupy only part of the
screen and can be partially transparent. The Activities behind them are either dimmed or
blurred.
A dialog is part of an activity, and its life-cycle is controlled by the activity that is built in. So
there is no need to add it to the manifest. Dialogs are an important part of an Android
application. They are used to show messages to user, show latest updates, take users input ...etc.
To achieve this purpose, you can use one of the following techniques:
1
2
3

Use Androids built-in Dialog sub-classes: These are Dialog boxes provided by Android
SDK. They all extend the Dialog class
Create an Activity and make it behave as a Dialog by changing its theme.
Toast: This is a special kind of message boxes that show up for a short period of time
then disappear. Toasts are not necessarily attached to an activitys lifecycle. Thats why
they preferred to be used with background services.

Dialog sub-classes
Android provides a set of Dialog sub-classes that youre recommended to use. These are:
AlertDialog A dialog that can manage zero, one, two, or three buttons, and/or a list of
selectable items that can include checkboxes or radio buttons. The AlertDialog is capable
of constructing most dialog user interfaces and is the suggested dialog type. See
Creating an Alert Dialog section later in this lesson.
ProgressDialog A dialog that displays a progress wheel or progress bar. Because it's
an extension of the AlertDialog, it also supports buttons. See Creating a Progress
Dialog later in this lesson.
DatePickerDialog A dialog that allows the user to select a date.
TimePickerDialog A dialog that allows the user to select a time.

Creating dialogs with user-defined layout


Although the set of Dialog sub-classes are sufficient to provide the notification necessary to the
user, you might need to create your own dialog. Here is how to do it:

Create layout resource, in the res/layout folder. Lets call the file dialog_view.xml
Create a variable of type Dialog and instantiate it.
Call setContentView(R.layout.dialog_view) for the dialog
Call show()

Android ATC 2012

42

final Dialog dialog = new Dialog(AndroidATCActivity.this);


dialog.setTitle("Dialog Title");
dialog.setContentView(R.layout.dialog_view);
TextView text = (TextView) d.findViewById(R.id.dialogBodyText);
text.setText("This is the text in my dialog");
dialog.show();

To edit the appearance of the whole dialogs window, you should get a reference to the dialogs
Window object. To do so, call:

Window window = dialog.getWindow();

You can modify the appearance of the Dialogs window simply by changing few flags. The
following makes the activity behind the dialog appear blurred, and changes the dialogs height
and width.
// Have the new window tint and blur the window it obscures.
Window window = dialog.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,WindowManager.Lay
outParams.FLAG_BLUR_BEHIND);
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);

To make the activity dimmed instead of blurred, simply replace


WindowManager.LayoutParams.FLAG_BLUR_BEHIND, with WindowManager.LayoutParams.FLAG_DIM_BEHIND

Always use dialog.show() and dialog.cancel() to show and hide a dialog respectively.

Android ATC 2012

43

Creating an Alert Dialog


AlertDialog is a Dialog-based class that takes up to three buttons and displays a message. Follow
the following steps to create an AlertDialog.
Extends Dialog class
Create and instantiate and instance of AlertDialog.Builder:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
Add required buttons:
alertDialog.setPositiveButton
alertDialog.setNegativeButton
Show dialog
ad.show()
The following code snippet builds an alert dialog and displays it. Notice that the code adds an
onClick listener to both buttons. One closes the dialog itself when clicked and other closes the
whole activity Activity using method finish().

AlertDialog alertD = new AlertDialog.Builder(this).create();


alertD.setTitle("Back?");
alertD.setMessage("Are you sure you want to exit?");
alertD.setButton(AlertDialog.BUTTON_NEGATIVE, "NO", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertD.setButton(AlertDialog.BUTTON_POSITIVE, "YES", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
((Activity)context).finish();
}
});
alertD.show();

Android ATC 2012

44

The following is the output of the code above.

Creating a Progress Dialog


This is a special dialog that shows a progress indicator and text message for the user. It has the
following features:

Extends Dialog class


Used to inform the user that a time-consuming process is undergoing.
It show a progress bar below a message or a an indefinite wheel (spinner) next to the
message.
ProgressDialog is an extension of AlertDialog. Thats why it also supports up to three
buttons with the following ids:
Dialog.BUTTON_NEGATIVE
Dialog.BUTTON_POSITIVE
Dialog.BUTTON_NEUTRAL
The following code snippet creates a progress dialog with one button, titled Cancel, and
it shows an wheel with a message next to it.

Android ATC 2012

45

Window window = dialog.getWindow();


ProgressDialog progressD = new ProgressDialog(this);
progressD.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressD.setButton(Dialog.BUTTON_NEGATIVE, "Cancel", new
OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
}
});
progressD.setMessage("Please wait. Loading...");
progressD.show();

When you run the code, youll get the following dialog

Android ATC 2012

46

To change the wheel to a progress bar, replace the following line in the code above:
progressD.setProgressStyle(ProgressDialog.STYLE_SPINNER);
with this line
progressD.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
Then you will get the following dialog:

You can add two more button to the progress dialog using Dialog.BUTTON_POSITIVE and
Dialog.BUTTON_NEUTRAL as the first parameter for method setButton() as used above

Activities with Dialog Theme


Although Dialogs provide a simple and lightweight mechanism to display screens and interact
with users, you can instead use an Activity for that purpose and style it to make it appear as a
Dialog.

Android ATC 2012

47

The simplest way to do so is by applying the dialog theme to your Activity in the manifest file.
The following XML snippet goes into your manifest and then your activity will appear like a
dialog:
<activity android:name=AndroidATCActivity android:theme=@android:style/Theme.Dialog>
</activity>

Toasts
Toasts are an easy way to deliver status messages to users without disrupting the current
working activity, because unlike Alert Dialogs they do not take focus away from the Activity.
Theyre suitable for displaying informative messages that dont need too much attention. For
example, it can be used to tell the user that a download has completed, or an email is sent.
Toasts fade away automatically after a certain period of time. Due to this nature, it may
not be guaranteed that a user will read the message. Thats why toasts are not used for critical
messages.
To create a toast only a single line of code is needed:
Toast.makeText(this, "Your download has resumed.", Toast.LENGTH_LONG).show();

The first parameter of makeText() defines the context in which its displayed. The second is
the message body and the last argument is and int that specifies how long the Toast should stay
on screen. Only Toast.LENGTH_LONG or Toast.LENGTH_SHORT are accepted values. Any
non-1 value is considered as a Toast.LENGTH_SHORT, and 1 is Toast.LENGTH_LONG.

A Toast message
Android ATC 2012

48

Customizing Toasts
Although showing a text message inside Toast is sufficient in most situations, but you might
need to customize your own Toast. To do that, you can set the layout of your own design and/or
change the Toasts screen position - by default a Toast is shown in the bottom of the screen.

To customize a Toast, follow these steps:


1

Create and instantiate a Toast object using the makeText() static method
Toast toast = Toast.makeText(this, "Hello World from Toast!",Toast.LENGTH_LONG);

Build the desired layout inside the java code:.


a Create a layout object
LinearLayout ll = new LinearLayout(context);

Create needed views


TextView tv = new TextView(context);
tv.setText("Message....");

Add the created layout using method setView()


toast.setView(ll);

Show the Toast


toast.show();

Toast class does not have method setContenView(), but rather the method
setView(). So you cant inflate a layout from an xml resource.

The following code snippet creates and displays a customized Toast. The toast contains a
message and a button, and its displayed at the top of the screen.
Toast toast = Toast.makeText(this, " ",Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);

LinearLayout ll = new LinearLayout(context);


ll.setOrientation(LinearLayout.VERTICAL);
ll.setBackgroundColor(Color.DKGRAY);

TextView tv = new TextView(context);


tv.setText("Hello World from a Customized Toast");

Android ATC 2012

49

Button btn = new Button(context);


btn.setText("

OK

");

btn.setPadding(10, 10,10,10);

ll.addView(tv,LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
ll.addView(btn, LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT);
ll.setGravity(Gravity.CENTER);
toast.setView(ll);

toast.show();

Here is the output:

Android ATC 2012

50

Methods to remember

Toast.makeToast()
The following methods in class Dialog
setTitle()
show()
cancel()
The following methods for a built-in Dialog subclass (ProgressDialog, AlertDialog,...etc.)
setMessage()
setButton()

Android ATC 2012

51

Lesson 7: More UI - Options Menu,


Context Menu, and WebView
Introduction
Menus are common user interface components used to present user actions and other options in
your activities. The menu that pops up when the user presses the Menu button is called
options menu and it supports icons. Each activity in an application can get its own options
menu.
Submenus are associated with menu items. Each item in the options menu can get its own submenu, which is a list of menu items shown in a floating window.

Menus
You can build a menu directly from Java code or from a resource file under res/menu.

Building a menu from Java code


To build a menu for an activity from Java code, follow these steps:
1
2

3
4

Inside the activity class, override the call-back method


onCreateOptionsMenu(Menu)
For each item you want to add to the menu call add() method.
Menu.add() takes 4 arguments, Group ID, menu item id (important for event
handling), order, and text.
Customize the menu item by calling MenuItem methods like setShortcut(),
setIcon()...etc.
Assign functionality to the MenuItem, either by calling setIntent() or overriding the
callback Activity method onOptionsItemSelected()

The following code snippet creates a menu in an Activity and adds two items to it, Settings and
Exit.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Create the menu item and keep a reference to it.
MenuItem menuItem1 = menu.add(Menu.NONE, Menu.FIRST, Menu.NONE,
"Settings");
MenuItem menuItem2 = menu.add(Menu.NONE, Menu.FIRST+1, Menu.NONE, "Exit");

Android ATC 2012

52

return true;
}

Notice that the method menu.add() returns a reference to the newly added
menu item and takes four arguments:
1
2
3
4

The group id that groups items in one category.


The menu item id - a unique identifier used for event handling.
The order within a group which can be used to change order of
appearance in a menu.
The text to show up in the menu.

Since options menu supports icons, you can set an icon using method setIcon() with a resource
id of an image that you have to add to folder res/drawable
menuItem1.setIcon(R.drawable.ic_menu_settings);

Then the menu will look like this:

Android ATC 2012

53

Building a menu from a resource file


To build an options menu from a resource file, follow these steps:
1
2

Create a new XML file under folder res/menu. If folder menu is not found, create the
folder.
Open the file in Eclipse to open the menu resource editor.

Add the required menu items by clicking Add..., and selecting Item from the pop up
window.

Then fill in the required attributes for the new item. Most importantly, fill in the item id
and the title fields.

Android ATC 2012

54

The Id field in the attributes form above is equivalent to the thirst parameter of
method add() explained before. This is a crucial attribute to handle event on a
menu item. Read section Handle Select Events later in this lesson for more
information.

Inside the activity class, override the call-back method


onCreateOptionsMenu(Menu)
Call Activitys method getMenuInflater().inflate(resourceId) where resourceId is
the name of the newly created XML file.

5
6

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}

Android ATC 2012

55

If you check the content of the menu resource file res/menu/activity_main.xml, it will look like
this:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_settings" android:title="@string/menu_settings"
android:icon="@drawable/ic_menu_settings">
</item>
<item android:id="@+id/exit_option" android:title="Exit">
</item>
</menu>

Handle Select Events


To handle the event of selecting an item and adding functionality to it, override the callback
method onOptionsItemSelected():

public boolean onOptionsItemSelected(MenuItem item) {


super.onOptionsItemSelected(item);
// Find which menu item has been selected
switch (item.getItemId()) {
// Check for each known menu item
case (Menu.FIRST): Log.v("menu item: ",item.getTitle()+"");return true;
case (Menu.FIRST+1): this.finish(); Log.v("menu item: ",item.getTitle()+"");return true;
default: Log.v("Default item: ",item.getTitle()+"");return true;
}
// Return false if you have not handled the menu item.
return false;
}

Note that returning false for any case means that the item selected is not handled, the code is
ignored, and Android will call the intent associated with the menu item if any exists.

Android ATC 2012

56

Sub-menus
You can create a submenu for an options menu item by following these steps:
1
2
3
4

Create a submenu object by calling method addSubmenu() of class Menu.


SubMenu sub = menu.addSubMenu()
Add submenu item using add() method:
MenuItem submenuItem = sub.add(...)
You can add an icon to the header of the submenu floating window using
sub.setHeaderIcon(...)
Optionally, you can make a submenu item a check box button by calling
menuItem.setCheckable(true)
Only radio buttons available in submenus.

Context Menus
Context Menus are associated to views and are triggered by pressing the View for around 3
seconds. So each Activity might have many context menus buy only one options menu.
You define and populate Context Menus similar to the options menu. You can also build a
context menu from Java code or from a resource file.

To create a context menu for a view:


1
2
3

Register the view for context menu with registerForContextMenu(view) inside an


activitys onCreate() method.
Override onCreateContextMenu() in the activity which takes three parameters.
Call method add() of class ContextMenu which is similar to add() method of class
Menu.

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle(Context Menu);
menu.add(0, menu.FIRST, Menu.NONE, Item 1).setIcon(R.drawable.menu_item);
menu.add(0, menu.FIRST+1, Menu.NONE, Item 2).setCheckable(true);
menu.add(0, menu.FIRST+2, Menu.NONE, Item 3).setShortcut(3, 3);

Android ATC 2012

57

SubMenu sub = menu.addSubMenu(Submenu);


sub.add(Submenu Item);
}

The context menu will look like this:

A context menu

MenuItem icons only show up in menus. Even if you call method setIcon() on
a MenuItem of context menus or submenus, the icon will not show up, just as
in the code above.

Handling Context Menu Selection


You can handle the selection in a context menu just you do in an options menu
Override method onContextItemSelected(MenuItem)

Android ATC 2012

58

Additional Menu Item options


The following is a set of MenuItem methods that adds optional customization to menu items.

Checkboxes and Radio Buttons


You can make items of a context menu or a submenu as checkboxes or radio buttons. To set a
Menu Item as a checkbox, use the setCheckable(true) method. Then you can make the item
checked or unchecked using using setChecked() and passing true or false as parameter.

Submenu made up of two check box options

A radio button group is a group of items displaying circular buttons, where only one item can be
selected at any given time. To create a radio button group, call Menu.setGroupCheckable(),
passing in that group identifier.

Submenu made up of two radio buttons

Shortcut Keys
Add a keypad shortcut to a menu item using method setShortcut()
// Add a shortcut to this menu item, 1 if using the numeric keypad
// or a if using the full keyboard.
menuItem.setShortcut('1', 'a');

Android ATC 2012

59

Icons
Icons are resource files saved under res/drawable folder. You can add icons to options menu
only using:
menuItem.setIcon(R.drawable.menu_item_icon);

Condensed Titles
When using icons with menu item in and option menu, you can use a shortened title for the
menu item using
menuItem.setTitleCondensed(Short Title);

Menu Item Click Listener


Although not recommended, you can handle click event for each menu item using method
setOnMenuItemClickListener().
menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem _menuItem) {
// ... execute click handling, return true if handled ...
return true;
}
});

Intents
You can assign an Intent to a Menu Item and trigger it when clicking it. This isnt handled by the
Activitys onOptionsItemSelected() or setOnMenuItemClickListener() handler. When triggered,
Android will execute startActivity, passing in the specified Intent. This is done using setIntent()
method.
menuItem.setIntent(new Intent(this, MyOtherActivity.class));

WebView
You can embed a web browser inside your application using web views. A WebView is a crucial
component for many applications that needs to display a URL without worrying about using
Androids native views. For example, an application that displays a list of article titles and loads
the full article upon clicking can display the article in a web view, instead of retrieving the
articles text and do the rendering and parsing inside the application.
Android ATC 2012

60

To include a web browser in your application:


1

Add the WebView widget in your activitys XML layout.

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


<WebView android:id="@+id/webView1" android:layout_width="match_parent"
android:layout_height="418dp"></WebView>

3
4
5
6

In your Activitys Java class, Create an instance of WebView in your Java Activity class
and initialize it:
webView = (WebView) findViewById(R.id.webView1);
Enable javascript in the WebView
webview.getSettings().setJavaScriptEnabled(true);
Set a WebView client that will receive various requests:
webview.setWebViewClient();
Send the URL request to display the page:
webView.loadUrl(url);
Give your application INTERNET permission to allow it to access the internet. To do
this, add the following tag to your Manifest XML file:

<uses-permission android:name="android.permission.INTERNET" />

Here is a code snippet that loads googles homepage into a WebView:


private WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browser_layout);
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
}

Android ATC 2012

61

Remeber to add the INTERNET permission to your manifest file. Otherwise,


youll get SecurityException.

Methods to remember

onCreateOptionsMenu()
onOptionsItemSelected()
onCreateContextMenu()
onContextItemSelected()
getMenuInflator().inflate(int menuRes);

Practical Exercise ( 1.5 hr)


Build an Android app with the following requirement:

The main activity takes username and password and a button that checks if credentials
are correct.
The second is a list activity that opens when the credentials are correct and shows a list
of universities.
Whenever each item is clicked, the browser opens to a Google URL searching for that
university name.
Each item in the list activity is a custom view with the background colored white and
foreground black.

Android ATC 2012

62

Lesson 8: Android Storage: Network,


File I/O, and Shared Preferences
Android Storage Options
Android provides several options to persist application data. The solution you choose depends
on your specific needs, such as whether the data should be private to your application or
accessible to other applications (and the user) and how much space your data requires.

Your data storage options are the following:

Shared Preferences
Store application-specific primitive data in key-value pairs.

Internal Storage
Store private data on the device memory using file I/O

SQLite Databases
Store structured data in a private database.
Android also provides Content Providers - an abstraction to SQLite databases to allow
sharing applications data. They encapsulate the data, and provide mechanisms for defining
data security.

Network Connection
Store data on the web with your own network server.

Connecting to the internet


As an android application developer, it is very likely that youll need to connect to the internet to
retrieve data, process it, and display it for the user. For example, a news application might need
to connect to a server over the web, retrieve a list of story titles, and display the stories in a
ListView.
Since most network-connected Android applications use HTTP to connect to the web, you will
need to use an HTTP client - a program that talks to a HTTP server. Natively, Android supports
two clients: HttpURLConnection and Apache HttpClient.

Android ATC 2012

63

Connecting to the internet in your application involves following steps:


1
2
3

Connect to an URL that retrieves data you can process (XML, JSON, ..etc)
Retrieve the data from the URL.
Process and manipulate retrieved data.

The following method connects to a URL and returns a string of the content retrieved:
private String connectToWeb() {
String url = "http://www.AndroidATC.com";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error for URL
" + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
byte[] buffer = new byte[128];
getResponseEntity.getContent().read(buffer);
return new String(buffer);
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}

File I/O
Reading and writing from/into local files in Android is purely java-based. To write to a file you
should create a FileOutputStream instance and to read from a file create a FileInputStream.
String FILE_NAME = tempfile.tmp;
// Create a new output file stream thats private to this application.
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
// Create a new file input stream.
FileInputStream fis = openFileInput(FILE_NAME);
Android ATC 2012

64

Yet, you can include a file as an Android resource, and read it from the resource folder.

Including files as resources


To read a file as a resource:
1
2
3

Create resource in res/raw


Add your file in the folder
Access the file from the Java code using getResources().openRawResource(id)
Resources myResources = getResources();
InputStream myFile = myResources.openRawResource(R.raw.myfilename);

Shared Preferences
Shared Preferences is a very useful and simple mechanism to permanently store data of your
Android application. This is the recommended way of storing data if primitive data types are all
you need to store.
Shared Preferences are a key-value pairs used for accessing and modifying preference data, and
support all primitive types. You can get an instance of a Shared Preferences object by calling
getSharedPreferences(String, int) in any activity. For any particular set of
preferences, there is a single instance of this class that all clients share.
After you get the instance you should use SharedPreferences.Editor object to modify
preferences and ensure the preference values remain in a consistent state and control when they
are committed to storage.

The following code uses SharedPreference to save data of a primitive types. Notice that the
preferences name is the value mySharedPreferences of string constant MY_PREFS.
public static final String MY_PREFS = mySharedPreferences;
protected void savePreferences(){
// Create or retrieve the shared preference object.
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS,
mode);
// Retrieve an editor to modify the shared preferences.
SharedPreferences.Editor editor = mySharedPreferences.edit();
// Store new primitive types in the shared preferences object.
editor.putBoolean(isTrue, true);
editor.putFloat(lastFloat, 1f);
editor.putInt(wholeNumber, 2);
Android ATC 2012

65

editor.putLong(aNumber, 3l);
editor.putString(textEntryValue, Not Empty);
// Commit the changes.
editor.commit();
}

You must call method commit on the SharedPreferences.Editor object, to save your
preference permanently. Its not enough to put the values in the object.

Retrieving Shared Preferences


After saving preferences, you can retrieve them in any other activity of the application, at any
other time (even after you close the application and reopen it). Reading shared preferences is as
simple as writing them. All you need to know is the key of the shared preference the type of
value stored i.e. whether its string, int, boolean,...etc.
public void loadPreferences() {
// Get the stored preferences
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,
mode);
// Retrieve the saved values.
boolean isTrue = mySharedPreferences.getBoolean(isTrue, false);
float lastFloat = mySharedPreferences.getFloat(lastFloat, 0f);
int wholeNumber = mySharedPreferences.getInt(wholeNumber, 1);
long aNumber = mySharedPreferences.getLong(aNumber, 0);
String stringPreference;
stringPreference = mySharedPreferences.getString(textEntryValue,);
}

Save activity state


One of the best scenarios to use shared preferences is saving the UI state of an activity. Suppose
an activity in your application contains a set of form widget (i.e. text fields, text views,
checkboxes...etc.), and you after filling the form out partially, the user gets a call and is forced to
exit the application. In this case, the user will lose all his/her input and will be required to reenter it again, unless the application developer; i.e. you, saves the activity state. This can be done
using shared preferences as well.
Whenever the user resumes an activity you load the preferences you have save when he/she
paused it. In other words you can save an activity state in four simple steps :
1. Create a method to save the state of an activity. Lets call it saveActivityPreferences()

Android ATC 2012

66

protected void saveActivityPreferences(){


// Create or retrieve the activity preferences object.
SharedPreferences activityPreferences =
getPreferences(Activity.MODE_PRIVATE);
// Retrieve an editor to modify the shared preferences.
SharedPreferences.Editor editor = activityPreferences.edit();
// Retrieve the View
TextView myTextView = (TextView)findViewById(R.id.myTextView);
// Store new primitive types in the shared preferences object.
editor.putString(currentTextValue,
myTextView.getText().toString());
// Commit changes.
editor.commit();
}

2. Create another method to load the saved activity state. Lets call it
loadActivityPreferences()
public void loadPreferences() {
// Get the stored preferences
int mode = Activity.MODE_PRIVATE;
SharedPreferences
mySharedPreferences = getSharedPreferences(MYPREFS,
mode);
// Retrieve the saved values.
boolean isTrue = mySharedPreferences.getBoolean("isTrue", false);
float lastFloat = mySharedPreferences.getFloat("lastFloat", 0f);
int wholeNumber = mySharedPreferences.getInt("wholeNumber", 1);
long aNumber = mySharedPreferences.getLong("aNumber", 0);
String stringPreference;
String stringEditValue;
stringPreference = mySharedPreferences.getString("textEntryValue", "");
stringEditValue = mySharedPreferences.getString("currentTextValue","test")
;
addTodoEditText.setText(stringEditValue);
Log.v("loadedpref",stringEditValue);
}

3. Override the Activitys onPause() call-back method to call method


saveActivityPreferences()
@Override
protected void onPause(){
super.onPause();
Log.v("AndroidACT","paused");
savePreferences();
}
Android ATC 2012

67

4. Override the Activitys onResume() call-back method to call loadActivityPreferences()


@Override
public void onResume() {
super.onResume();
loadPreferences();
Log.v("AndroidACT","resumed");
}

Android ATC 2012

68

Lesson 9: Android Storage: SQLite and


Content Providers
Introduction
SQLite is an Open Source Database system embedded into every Android device.
Using a SQLite database in Android does not require any database setup or administration.
You only have to define the SQL statements for creating and updating the database. Afterwards
the database is automatically managed for you by the Android platform. SQLite is a good
choice for being a mobile-embedded database system for being lightweight and open source

SQLite in your application


If your application creates a database, this database is by default saved in the directory
/DATA/data/application_name/databases/DATABASE_FILE.
Where APP_NAME is your application name and DATABASE_FILE is the name you specify in
your Java code for the database. Thats why the database names should be unique in your
application.

SQLite library
To use SQLite database in your application you need to import package android.database.*
To use databases in Android code, you have to learn about the following classes:

SQLiteOpenHelper
SQLiteDatabase
Cursor

SQLiteOpenHelper
This is a helper class to manage database creation and version management. It is
recommended that you create a subclass of SQLiteOpenHelper implementing
onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and optionally
onOpen(SQLiteDatabase). This class takes care of opening the database if it exists,
creating it if it does not, and upgrading it as necessary. Transactions are used to make sure the
database is always in a sensible state.

SQLiteDatabase
SQLiteDatabase exposes methods to manage a SQLite database. It has methods to create, delete,
execute SQL commands, and perform other common database management tasks.

Android ATC 2012

69

Cursors
The Cursor interface provides random read-write access to the result set returned by a database
query. So, it is a just pointer to the data returned by a database query, it doesn't contain all the
data from your query. But rather used facilitate access to each row of your returned data.

Databases in Android
Here is a set of steps to create and manipulate SQLite databases in Android:
1. Create an adapter class
2. Create an inner private class extend SQLiteOpenHelper
3. Create class constructor
public MyDBAdapter(Context _context) {
context = _context;
dbHelper = new myDbHelper(context, DATABASE_NAME, null,
DATABASE_VERSION);
}

4. Create inner class constructor:


public myDbHelper(Context context, String name, CursorFactory
factory,
int version) {
super(context, name, factory, version);
}

5. Override onCreate()
6. Override onUpgrade()
public void onUpgrade(SQLiteDatabase _db, int _oldVersion,
int _newVersion) {
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(_db);
c}

7. Create method open()


dbHelper = new myDbHelper(context, DATABASE_NAME, null,
DATABASE_VERSION);
SQLiteDatabase db;
try {
db = dbHelper.getWritableDatabase();
}
catch (SQLiteException ex){
db = dbHelper.getReadableDatabase();
}
Android ATC 2012

70

8. Create DB operations (delete, update, get, insert)


a. Querying
// Return all rows for columns one and three, no duplicates
String[] result_columns = new String[] {KEY_ID, KEY_COL1,
KEY_COL3};
Cursor allRows = myDatabase.query(true, DATABASE_TABLE,
result_columns,
null, null, null, null, null, null);
// Return all columns for rows where column 3 equals a set
value
// and the rows are ordered by column 5.
String where = KEY_COL3 + = + requiredValue;
String order = KEY_COL5;
Cursor myResult = myDatabase.query(DATABASE_TABLE, null, where,
null, null, null, order);

b. Inserting
// Create a new row of values to insert.
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]
// Insert the row into your table
myDatabase.insert(DATABASE_TABLE, null, newValues);

ContentValues is a class used to store a set of values that the SQLiteDatabase


object can process.
c. Updating
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]
String where = KEY_ID + = + rowId;
// Update the row with the specified index with the new values.
myDatabase.update(DATABASE_TABLE, updatedValues, where, null);

d. Deleting
myDatabase.delete(DATABASE_TABLE, KEY_ID + = + rowId, null);

Android ATC 2012

71

Native Android Content Providers


Android allows you to access some of its system resources using Content Provider - a layer that
facilitates access to Android SQLite DB. You can, for example, query all the phones contacts
using the contacts URI provided by Androids People class.
The following shows how to receive the name and phone number of every contact in your phone
book:
// Get a cursor over every contact.
Cursor cursor = getContentResolver().query(People.CONTENT_URI,
null, null, null, null);
// Let the activity manage the cursor lifecycle.
startManagingCursor(cursor);
// Use the convenience properties to get the index of the columns
int nameIdx = cursor.getColumnIndexOrThrow(People.NAME);
int phoneIdx = cursor.getColumnIndexOrThrow(People.NUMBER);
String[] result = new String[cursor.getCount()];
if (cursor.moveToFirst())
do {
// Extract the name.
String name = cursor.getString(nameIdx);
// Extract the phone number.
String phone = cursor.getString(phoneIdx);
result[cursor.getPosition()] = name + ( + phone + );
} while(cursor.moveToNext());

You must add the READ_CONTACTS permission, to allow your application to


access the phone book

Methods to remember
Class SQLiteDatabase SQL-commands methods:
o query()
o delete()
o insert()
o update()
getContentResolver().query()
startManagingCursor()
Cursor class methods like:
o getColumnIndexOrThrow()
o getString()
o getPosition()
o moveToNext()
Android ATC 2012

72

Lesson 10: Android Notifications


Introduction
Android provides a system service called Notification Manager which is used to handle
notifications from different applications. Using this service you can created new notification at
certain events in your application, modify existing applications, or cancel notifications no longer
needed.
Notifications are viewed in the notification bar and when clicked it can open an activity.

Creating a notification
To create notifications you should use the NotificationManager class which can be created
in an Activity using the getSystemService() method.
NotificationManager MyNotificationManager
= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

Notification actions
Although they're optional, you should add at least one action to your notification. An action
allows users to go directly from the notification to an Activity in your application.

Android ATC 2012

73

You should always define the action that's triggered when the user touches the notification;
usually this action opens an Activity in your application. You can add more actions by adding
more UI elements to the notification (like a button) and assign them other on click actions.
Inside a Notification, the action itself is defined by a PendingIntent containing an Intent
that starts an Activity in your application. Here how to create a notification and an explicit
Intent to be used by a PendingIntent.

// Create Notifcation
Notification notification = new Notification(R.drawable.icon, "Hello notifications!",
System.currentTimeMillis());
// Cancel the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.number += 1;
// Specify the called Activity
Intent intent = new Intent(this, NotificationReceiver.class);

You use then a PendingIntent to assign the Intent to the notification and finally assign
it to the NotificationManager.
PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, "This is the title", "This is the text", activity);
notificationManager.notify(0, notification);

Example: NotificationManager
Create a new project "com.androidatc.notificationmanager" with the Activity
"CreateNotification".
result.xml
Create the following layout "result.xml".
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/andro
id"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the result activity opened from the
notification" >
Android ATC 2012

74

</TextView>
</LinearLayout>

main.xml
This layout is automatically created when you created the project. Modify it as the following:
<?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" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="createNotification"
android:text="Create Notification" >
</Button>
</LinearLayout>

NotificationReceiver.java
Create a new activity "NotificationReceiver" and register the acitivity in the manifest file.
package com.androidatc.notificationmanager;
import android.app.Activity;
import android.os.Bundle;
public class NotificationReceiver extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
}
}

Android ATC 2012

75

CreateNotification .java
Change the activity "CreateNotification" to the following.
package com.androidatc.notificationmanager;
import
import
import
import
import
import
import

android.app.Activity;
android.app.Notification;
android.app.NotificationManager;
android.app.PendingIntent;
android.content.Intent;
android.os.Bundle;
android.view.View;

public class CreateNotification extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void createNotification(View view) {
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon,
"A new notification", System.currentTimeMillis());
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, "This is the title",
"This is the text", activity);
notification.number += 1;
notificationManager.notify(0, notification);
}
}

When you run your application, press the button and you should receive a new notification. If
you select it, your second activity will be displayed.

Android ATC 2012

76

Summary
Briefly, creating and configuring a notification requires the following simple steps:
1. Create a NotificationManager object:
String svcName = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager;
notificationManager = (NotificationManager)getSystemService(svcName);

2. Create notification object


// Choose a drawable to display as the status bar icon
int icon = R.drawable.icon;
// Text to display in the status bar when the notification is launched
String tickerText = Notification;
// The extended status bar orders notification in time order
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);

3. Configure appearance
Context context = getApplicationContext();
// Text to display in the extended status window
String expandedText = Extended status text;
// Title for the expanded status
String expandedTitle = Notification Title;
// Intent to launch an activity when the extended text is clicked
Intent intent = new Intent(this, MyActivity.class);
PendingIntent launchIntent = PendingIntent.getActivity(context, 0,
intent, 0);
notification.setLatestEventInfo(context,expandedTitle, expandedText,
launchIntent);

4. Trigger the notification


int notificationRef = 1;
notificationManager.notify(notificationRef, notification);

5. Optionally, you can cancel the notification after triggering it:


notificationManager.cancel(notificationRef);

Android ATC 2012

77

You might also like