0% found this document useful (0 votes)
99 views72 pages

Mad Technical Book 3161612

The document provides an overview of the Android platform, detailing its architecture, application components, and development environment. It discusses the advantages and disadvantages of Android, including its open-source nature and support for various programming languages. Additionally, it outlines key APIs and the importance of the AndroidManifest.xml file for application development.

Uploaded by

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

Mad Technical Book 3161612

The document provides an overview of the Android platform, detailing its architecture, application components, and development environment. It discusses the advantages and disadvantages of Android, including its open-source nature and support for various programming languages. Additionally, it outlines key APIs and the importance of the AndroidManifest.xml file for application development.

Uploaded by

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

1 Overview of Andr

oid·
Syllabus
Introducing Android,
The Android Applic
Installing Android, Exp ation Components,
loring the Develop The manifest file, D
m en t ownloading and
AndroidApplication Environment, Devel
oping and Executing the first

Contents
1.1 Introduction to And
roid
1.2 Android APls
1.3 Android Archite
cture
1.4 Android App
lication Framewor
k
1.5 Android App
lication Compone
nts
1.6 Exploring th
e Development E
nvironment
1. 7 Android Devel
oping Tools
1.8 Developing A
ndroid Application
1. 9 Developing A
ndroid Application
On Eclipse Platform
1.1 o Short Questio
ns and Answers
Multiple Choice Q
uestions

(1 - 1)
Mobile Application Development 1-2
Overview of Android

m Introduction to Android
• Android is an open-source software development platform. for creating mobile
applications.
• Android is an open source software stack that includes :
1. Operating system : Linux operating system kernel that provides low level
interface with the hardware, memory management and process control.
2. Middleware : A run time to execute Android applications.
3. Key mobile applications : Email, SMS, PIM, web browser and etc.
4. Along with API libraries for writing mobile applications : Including
open-source libraries such as SQLite, WebKit and OpenGL ES.
• The components of the underlying OS are written in C or C ++, user applications
are built for Android in Java. Even the built-in applications are written in Java.
• An important feature of the Android platform is that there's no difference between
the built-in applications and applications that is create with the Software 1

Development Kit (SOK).


• Android is only a software. By leveraging its Linux kernel to interface with the
hardware, Android runs on many different devices from multiple cell phone
manufacturers. Developers write applications in Java.
• The Android software environment and hardware it runs on is shown in Fig. 1.1.1.

··:.· .· -:""'.;··. ·. ·

.•· Custom ·•· ·


applications·
•·•n Java

Fig. 1.1.1 Android OS Design and Features

__________ Ti_E_C_H_N_IC_A_L_P_U_B_L_IC-A~Ti=,o-=-N~s:=i®~_-:A-=n~u=p-:th=ro:s:t~fo=,~k:no:wl:e:d~g~e
-----
---
~ ucation Development
-- ---------------~~~ 1- 3
Overviewof Android
- Advantages and Disadva
ntagesof Android
~~
ges of Android OS
~d~anta
.
. supports 20, 3D grap
1 hics· It supports various platfor
ms like 2D and 3D.
_ supports multiple language
2 s - Android supports differe
nt languages
3. Java support · The Java su
pporting feature enables
features. developers to enhance m
ore
4, Faster web browser - Easily loads
multimedia so that it m
faster. akes web browsing

5. Supports MP4, 3GP, MPEG4, MID


I - It supports different ty
There is no need to co pes of formats.
nvert from one format
different formats of audio to another, as it enabled
and video styles . with
6. Video calling - Faster
data connection enables
to do video call.
7. Open source framew
ork - users can make th
changes eir own applications an
d make
s. Uses of tools are very sim
ple
9. Social networking in
tegration - Free to custom
using user enabled develo ize the applications and
pment. features,
10. Better notification sy
stem - It makes users to
directly from the dashboar check important notifica
d. tions
11. Low chance of crashi
ng - The Android OS is ve
and less chances of crashi ry smooth and easy to
ng down. operate
12. Stability - Stability an
d security is better than
Linux Kernel. other mobiles OS as it is
based on

Disadvantages of Android
OS
1. Slow response - Com
pared to 'ios' of Apple,
open same app in the io Windows of Microsoft.
s and Windoes 8. We ob when we
android when we open ap se rv e the slow response of
ps in the different platfor the
2· Heat m s.
- Compared to other oper
ating systems Android m
efficient. This makes proc akes use of processes ve
essor to get heat. Some ry
reduce heat, but it went ha rd wa re co m pa ni es take care to
in vain when we operate
battery. it a long time and at
low
3
· Advertisement - When
we use an Android app
between application use, we encounter several ad
because anyone can mak ds in
the app program and can e ad d by inserting some logic in
interfere in into the phon
es information.

TECHNICAL PUBLICATIO ®
NS - An uo th
---
1-4 Overview of AndfOla
Mobile Application Development

Ill Android APls


• Android offers a number of APis for d~v~lop~g your a~plica~ons. The folloWing
list of core APis should provide an insight into whats available; all Anclroid
devices will offer support for at least these APis :
l. android.util _ The core utility package contains low-level classes like specialized
containers, string formatters, and XML parsing utilities.
2. android.as - The operating system package provides access to basic operating
system services like message passing, interprocess communication, clock
\ functions and debugging.
3. android.graphics - The graphics API supplies the low-level graphics classes that
support canvases, colors and drawing primitives and lets you draw on canvases.
4. android.text - The text processing tools for displaying and parsing text.
5. android.database - Supplies the low-level classes required for handling cursors
when working with databases.
6. android.content - The content API is used to manage data access and publishing
by providing services for dealing with resources, content providers and
packages.
7. android.view - Views are the core user interface class. All user interface elements
are constructed using a series of Views to provide the user interaction
components.
8. android.widget - Built on the View package, the widget classes are the "here's
one we created earlier" user-interface elements for you to use in your
applications. They include lists, buttons and layouts.
9. com.google.android.maps - A high-level API that provides access to native map
controls that you can use within your application. Includes the Map View control
as well as the Overlay and MapController classes used to annotate and control
your embedded maps.
10. android.app - A high-level package that provides access to the application
model. The application package includes the Activity and Service APis that form
the basis for all your Android applications.
11. android.provider - To ease developer access to certain standard Content
Providers (such as the contacts database), the Provider package offers classes to
provide access to standard databases included in all Android distributions.
12. android.telephony - The telephony APis give you the ability to directly interact
with the device's phone stack, letting you make, receive and monitor phone calls,
phone status and SMS messages.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
, ApplicationDevelopment _
1 5
1
!vfob'!---:..-
,,,,------ ---- ~~------- _:_=-:__________ Overviewof Android

- The WebKit p~ ka
13. android.webkit . features APis for working with
Web-based content, including a WebVi
control for embedding browsers in
your activities and a cookie manager. ew

Ill Android Architecture


• Following are the different layers in the Android stack .
1. Linux kernel layer ·

2. Native layer
3. Application framework layer
4. Applications layer
Fig. 1.3.l illustrates android stack.

Fig. 1.3.1 Android stack

1. The Linux kernel layer


• The Linux kernel includes drivers for hardware, networking, file system access
and inter-process-communication.
• The Linux kernel is at the bottom of the Android stack. It never really interacts
with the users and developers, but is at the heart of the whole system.
Its
importance stems from the fact that it provides the following functions in the
Android system :
a) Hardware abstraction
b) Memory management programs
C) Security settings
d) Power management software
e) Other hardware drivers (Drivers are programs that control hardware devices.)

knnwlArlaA
1- 6
Overviewof Android
~M~ob~il~e~Ap~p~/ic~a~tio~n~D~e~ve~lo~p~m~en~t
__ ____ .!..:~-------------- ._
f) Support for shared libraries
g) Network stack

2 . Native code llbrarles l_


ayer .
. the Andr01d archit ecture includes Android's native libraries
• The next layer m . . . . ·
t of tO anide the device m han dlin g dif
Libraries carry a se ins tru ctio ns r,- fer ent typ es
b
of data. For instance, the play ack and recording of various audio and video
.
. "d
formats 1s gw e d by the me dia fra me wo rk hbrary.
. . d . .
• The native libranes me 1u es d em ons and ser vic es (w ntt en m
a . C or C++) like
t dat .
abase support via SQLite, advanced
browser technology fr om WebI<i , graphics
support ( D, 0 and animation from .
2 3 scalable games language), audio and .
video
media support from PacketVideo's Op
enCORE.
Android Runtime
• The Android runtime are written
in Java and executing in Dalvik. Th
packages used for a full-featured Jav e core Java
a programming environment and the
VM, employs services of the Linux-bas Dalvik
ed kernel to provide an environment
Android applications. to host

• Dalvik is open-source software. It


is the software responsible for runnin
Android devices. g apps on

3. Application framework layer


• An important block of app
lication framework is application manager. The
application managers include window
s, contents, activities, telephony, loc
notifications. ation and

4. Application layer
• The applications are at the topmo
st layer of the Android stack. An ave
the Android device would mostly inte rage user of
ract with this layer (for basic functio
as making phone calls, accessing the ns, such
Web browser etc.).
• The layers further down are access
ed mostly by developers, programm
likes. ers and the

• Several standard applications com


e installed with every device, such
a) SMS client app as :
b) Dialer
c) Web browser
d) Contact manager

TECHNICAL PUBLICATIONS®- An ""


th ... , .. ,
fication Development 1-7 Overviewof Android

,0 Android Application Framework .


A plication framework : The application framework provides the classes used to
' p t Android applications. It also provides a generic abstraction for hardware
crea e
and manages the user interface and application resources.
acceSs
, The Android application framework provides everything necessary to implement
your average application. The Android application lifecycle involves the following
key components : . .
1. Activity Manager - Controls all aspects of the application lifecycle and activity
stack.
2. Content Providers - Allows applications to publish and share data with other
applications.
3. Resource Manager - Provides access to non-code embedded resources such as
strings, color settings and user interface layouts.
4. Notifications Manager - Allows applications to display alerts and notifications
to the user.
5. View System - An extensible set of views used to create application user
interfaces.
• The Android application framework includes traditional programming constructs,
such as threads and processes and specially designed data structures to
encapsulate objects commonly used in mobile applications. Developers can rely on
familiar class libraries, such as java.net and java.text. Specialty libraries for tasks
such as graphics and database.
• Android applications can interact with the operating system and underlying
hardware using a collection of managers. Each manager is responsible for keeping
the state of some underlying system service. For example, there is a
LocationManager that facilitates interaction with the location-based services
available on the handset.
• The v·1ewManag
er and WindowManager manage user interface fundamentals.
Applications can interact with one another by using or acting as a
ContentProvider.
• BUilt-in a li .
third PP ca~ons_such as the Contact manager are content providers, allowing
Wa party applications to access contact data and use it in an infinite number of
ys. The sky is the limit.
1-8 Overviewof Andro/a

1111 Manifest File


• Every application must have an AndroidManifest.xml file (with precisely that
name) in its root directory. The manifest presents essential information about the
application to the Android system, information the system must have before it can
run any of the application's code. Among other things, the manifest does the
following:
1. It names the Java package for the application. The package name serves as
a,
unique identifier for the application.
2. It describes the components of the application - the activities, services,
broadcast receivers, and content providers that the application is composed of.
It names the classes that implement each of the components and publishes
their capabilities (for example, which Intent messages they can handle). These
declarations let the Android system know what the components are and under
what conditions they can be launched.
3. It determines which processes will host application components.
4. It declares which permissions the application must have in order to access
protected parts of the API and interact with other applications.
5. It also declares the permissions that others are required to have in order to
interact with the application's components.
UVt7# vnm v, , "·-· - · .
1- 9
pficationDevelopment
. pro fili ng and other information
nta tio n cla sse s tha t pro vid e
lists the Instrume
6_ It run nin g. Th ese dec lar ations are present in the manifest
as the app lica tio n is
oved
y wh ile the app lica tio n is bei ng developed and tested; they're rem
onl ..
before the app lica tio n is pub lish ed .

the mi nim um lev el of the An dro id API that the application requires.
es
7_ It declar
linked against.
_ It list s the libraries that the application must be
8

1111 Downloading and Installing Android


ent for
ite An dro id app lica tio ns, one mu st configure programming _environm
, To wr
. Th e sof twa re is ava ilab le onl ine for download at no cost.
Java development
lica tio ns can be dev elo ped on Wi ndows, Macintosh, or Linux systems.
Android app
dro id app lica tio ns, you nee d to have the following software
, To develop An
installed on computer :
a De vel opm ent Kit (JD K) Ve rsio n Sor 6, available for download at
1. The Jav
/index.jsp.
http://j ava.sun.com/javase I downloads
se along with its JOT plug-in, ava
ilable for
pat ibl e Jav a ID E suc h as Ec lip
2. A com
/ downloads/.
download at http: //www .eclipse.org
ation, available for download at
3. The Android SOK, tools and document
x .html.
http:// developer.android.com/sdk/inde
vel opm ent To ols (AD T} plu g-i n for Eclipse, available for
4. The Android De
h the Ec lip se sof twa re upd ate mechanism. For instructions on
download thr oug l.
ins tall thi s plu g-i n, see htt p:/ /de vel oper.android.com/sdk/eclipse-adt.htm
how to nd to
gh thi s too l is opt ion al for dev elopment, but it is highly recomme
• Althou
install it.
License
An dro id SO K com es wit h fiv e ma jor components : the Android SOK
• The Framework, Tools and
dro id Do cum ent atio n, Ap pli cat ion
Agreement, the An
Sample Applications.
onment
Exploring the Development Envir
hav e sev era l cho ice s wh en it comes to integrated development
• Developers le
ent s (ID Es) . Ma ny dev elo per s cho ose the popular and freely availab
environm
droid applications.
Eclipse IDE to design and develop An
re is an
ips e is the mo st pop ula r IDE for Android development, and the
• Ecl
g Android development.
Android plug-in available for facilitatin
s :
An dro id app lica tio ns can be dev elo ped on the following operating system

t or 64-bit)
• Windows XP (32-bit) or Vista (32-bi
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
1 - -, v

Mobile Application Development

8 later (x86 only)


• Mac OS X 10.5. or 8 04 LTS, Hardy Heron)
LlnUX Ubuntu · E li se Integrated Development Envirorun
• Linux(tested on ent
the popular c An P
st dev elo per s use Th droid development team has integrated
• Mo develope
(IDE) for Android developmelntd.rre
. c~y into the Eclipse IDE. However, rs
d d evelop· ment. too sli . they can also use oth er IDE s.
the Androi Ee pse ,
are not constrained to usin g

ID Android Developing Tools


:
Various Android development tools are

Android SOK
An dro id Sof twa re Dev elo pm ent Kit (Android SOK) contains the necessary
• The are
droid applications. Most of these tools
tools to create, compile and package An
command line based. a
prim ary way to dev elo p An dro id applications is based on the Jav
• The
programming language.
d from Android website.
• Android SDK can be freely downloade
Android Debug Bridge (ADB)
An dro id SD K con tain s the An dro id Debug Bridge (ADB), which is a tool that
• The of
real Android device, for the purpose
allows you to connect to a virtual or
r application.
managing the device or debugging you
id Studio
Android Developer Tools and Andro
Development Environments (IDEs) to develop
• Google provides two Integrated
new applications.
dro id Dev elo per Too ls (AD T) are bas ed on the Eclipse IDE. ADT is a set of
• The An ent
pon ent s (plu g-in s), wh ich ext end the Eclipse IDE with Android developm
com
capabilities.
droid
ogl e also sup por ts an IDE call ed Android Studio for creating An
• Go
IntelliJ IDE.
applications. This IDE is based on the
deplo y
h IDE s con tain all req uire d fun ctio nality to create, compile, debug and
• Bot virtual
dro id app lica tion s . The y also allo w the developer to create and start
An
Android devices for testing.

Dalvlk Virtual Machine (DVM) to nw


use s the Dal vik virt ual ma chi ne with just-in-time compilation
• Android
slated from Java byte code.
Dalvik byte code, which is usually tran

®
ATIONS - An up thrust for knowledge
1 - 11 Overview of Android
. ticstion Development

is an
ding to Goo gle's Android documentation ' the Dalvik VM
, .ACCOr . .
the Dalvik Executable (.dex)
. terpreter-onlyvirtUal machine that executes files in
ge and memory-mappable"
:rinat, a format that is optimized for efficient stora
execution.
run classes compiled by a Java
, The virtual machine is register-based and it can
native format.
language compiler that have been transformed into its
al machine. The latest Android
, currently Android versions use the Dalvik virtu
Time.
versions introduced a new runtime the Android Run

Android RunTime (ART)


RunTime (ART) as optional
• With Android 4.4, Google introduced the Android
ime for all Android versions
runtime for Android 4.4. It is uses as default runt
after 4.4.
the deployment process of an
• ART uses Ahead of Time compilation. During
is translated into machine
application on an Android device, the application code
piles code, but allows faster
code. This result in approximately 30 % larger com
executionfrom the beginning of the application.
only done once, during the first
• This also saves battery life, as the compilation is
start of the application.
the Android tool change and
• The dex2oat tool takes the .dex file created by
at (ELF file). This file contains
compiles that into an Executable and Linkable Form
Keeping the .dex code allows
the dex code, compiled native code and meta-data.
that existing tools still work.
to reduce times in which the
• The garbage collection in ART has been optimized
applicationfreezes.

Developing Android Application


Java programming language.
• Android applications are primarily written in the
roid specific configuration files
• During development the developer creates the And
ing language.
and writes the application logic in the Java programm
application files, transparently
• The ADT or the Android studio tools convert these
to the user, into an Android application.
IDE, the whole Android
• When developers trigger the deployment in their
ed.
application is compiled , packaged, deployed and start

ledge
TECHNICAL PUBLICATIONS®- An up thrust for know
. . Development 1-1 2 Overviewof A
Mobile Appllcst10n ne1%
_.... Code to Android A
version Process from source pplication
U:.IU Con
d to Java class files by
• The Java source files are converte the Java compiler.
. ·tams a all d dx which conver
• The Android SDK 1
too c e ts Java class files t
con . cl as s . .
files of the applicatio
in
·

.dex (Dalvik Executable) file. All n are placed in this o a


.d
file. ex
. dundant information
• During this conversion process re in the class files a
timized in the dex fil . . . f
\ op e.For examp1e, if the same String 1s oun d m.
di
. re
·
files, the .dex file cont fferent clas
ains only on f of this String s
e re erence
.
• These .dex files ar h f .
e t ere ore muc h smaller in size than the
corresponding class
files.
• The .dex file and th
e resources of an A
files, are packed into ndroid project, e.g.,
an .apk (Android pa the images and XML
ckage) file. The prog
Asset Packaging Tool ram aapt (Android
) performs this step.
• The resulting .apk
file contains all nece
ssary data to run th
and can be deployed e Android applicatio
to an Android device n
via the adb tool.
il;f j Android SOK Featu
res
• Important features
of Android SOK are
as under.
1. No licensing, dist
ributions or developm
ent fees or release ap
2. Full multimedia proval processes.
hardware control.

I
3. APls for using se
nsor hardware includ
ing accelerometer an
4. APls for location d the compass.
based services.
5. Android Inter-Pr
ocess Communication
(IPC).
6. Shared data storag
e.
7. Background applicatio
ns and processes.
8. Home screen wid
gets, live folders.
9. HTMLS WebKit-
based web browser.
10. GSM, EDGE and
3G networks for tele
phony and data trans
l l. The Android SO fer.
K includes developm
debug any app. ent tools which he
lps compile and
12
· An~roid emulator
device. shows how app will
look and behaviour
on a real Andro id

TECH
Overview of Androki
1 - 13
. t1on Development
·1e APP11cs
' ping Android Application On Eclipse Platform
oeve10
E hich is software that
. an Integrated Development Environment, or ID , w .,
Eclipse is · d debuggi ng your
' .d all the essential tools needed for editing, runrung, an
prov1 es
Java programs. . d . the
·s a set of development tools use lJ\
, The Java Deve1opmen t Kit, or JDK, l
programmingof Java applications.
. all d The JDK can be
, The Eclipse IDE requires that a JDK be loca 11y inst e •
downloaded from the web at
http://java.sun.com/ javase /downloads/ index.jsp.
reate a new Android Application
1. In Eclipse go to File->New->Project ...
2. Select an Android Project from the Android Folder and press Next.
3. Fill in the details of your Android application.
a. Project Name : The project name and folder that Eclipse will store the
project files.
b. Build Target: The version of the Android SDK that will be used when you
build your program. Select a platform that is equal to or lower than the
target chosen for the AVD.
c. Application Name : This is the name of the application.
d. Package Name : The namespace that all of the source code will reside under.
e. Create Activity : The name for that class stub that is generated by the
plugin.

4. The values that are used in this example are :


a. Project Name : SampleApp
b. Build Target : 2.3.3
c. Application Name: SampleApp
d. Package Name: com.sample.example
e. Create Activity: SampleApp
S. Click on Finish.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Activities
a n d F r a g m e n t s

1/labus nts, Fragments,


in A nd ro id W or ki ng w ith activities, Using Inte
fng Activities,Fragmen
ts and Intents
bj ec t to In vo ke B ui lt - in Application
!ng the Intent O

rJntents
1 Activity Lifecycle
id
2 Fragments in Andro
t
3 Life Cycle of Fragmen
4 Replacing Fragment
5 Intent
r Activity
6 Intent to Start anothe
Intent
7 lmplicir and Explicit
(AVD)
8 Android Virtual Device
Process
9 Mapping Application to
wers
10 Short Questions and Ans
11 Multiple Choice Questions
"!!'b ile Application [)evefopmen

Ell Activity
____
_
~_.=.:__-----Activ
2 2
---~~
ities and F
-
~
Lifecycle . ..
.
. .on compnse one or more activities. Because of the mobile
• Applicati . f an activity is governed by a set of states at\d lJ1
experience the operation o Oike ...
a fini~
chin e) called the lifecycle.
if the user receives a phone call or swit ch
a) Cras hin g es to another app Wh ;,
using your app. ute
4

b) Consuming valuable system resources whe


n the user is not actively using it
c) Losing the user's progress if they leav
e your app and return to it at a later
time.
d) Crashing or losing the user's progress
when the screen rotates between
landscape and portrait orientation.
• To navigate transitions between stages
of the activity lifecycle, the Activity class
provides a core set of six callbacks: onCreat
e(), onStart(), onResumeQ, onPauseo,
onStop(), and onDestroy().
• The system invokes each of these callbacks
as an activity enters a new state.
1. onCreate()

• This callback must be implemented, whi


ch fires when the system creates your
activity. Your implementation should initi
alize the essential components of your
activity: For example, your app should crea
te views and bind data to lists here.
Most importantly, this is where you mus
t call setContentView() to define the
layout for the activity's user interface.
• When onCreate() finishes, the next callback
is always onStart().
2. onStart()

• As onCreate() exits, the activity enters the Started state


, and the activity becomes
visible to the user . This callback contains
what amounts to the activity 's final
p reparations for coming to the foreground
and becoming interactive .
3. onResume()
• The sy stem invokes this callback just
before the activity starts interacting with the
user . At this point, the activity is at the top
of the activity stack , and cap tures all
user input . Most of an app 's core function
ality is implemented in the onRe sumeO
method .
• The onPause() callback always follows onR
esume{) .

TECHNICAL PUBLICATIONS® - An up thrus


t for knowledge
Activities ana r,a-::,-· ·

2-3
/icstion Development
p;teAPP
o Paused
paLlseO f cus and enters a
of1 alls onPause() when the activity loses o B k or Recents
, 'fhe ThiS state occurs when, for example, the user . . it technically means
state. When the system calls onPause() for your activ1~' . . that the user
button. t ft is an indication
. ·ty is still partially visible, but mos O en d Resumed
your acnv1 ti. ·ty and the activity will soon enter the Stoppe or
. ving the ac v1 ,
is 1ea
state. th UI if the user is
tivity in the Paused state may continue to update e h . g a
An ac . . . lude one s owm
' ting the UI to update. Examples of such an activity me . ..
expec . E .. f such activities 1ose
1
. an·on map screen or a media player playing. ven
nav1g
e user expects their UI to continue updating. k
f~,S th
. . d ta make networ
, You should not use onPause() to save application or user a ,
calls, or execute database transactions.
, Once onPause() finishes executing, the next callback is either onStop() or
onResume(), depending on what happens after the activity enters the Paused state .

. onStop()
, The system calls onStop() when the activity is no longer visible to the user. This
may happen because the activity is being destroyed, a new activity is starting, or
an existing activity is entering a Resumed state and is covering the stopped
activity. In all of these cases, the stopped activity is no longer visible at all.

• The next callback that the system calls is either onRestart(), if the activity 18
coming back to interact with the user, or by onDestroy() if this activity 18
completely terminating.
•onD&stroy()

• The system · k this


mvo es callback before an activity is destroyed.
• This callback 18· th final nD
. e one that the activity recei·ve
lihplemented to ens s. o estroy() is usually
activity ure that all of an activity's resources are released when the
'or the process containing it, is destroyed .
Mcuv1c1es and F
2 - 4 ------------- rageme,11~
. oeve/opment
Mobile Appficst1on

on Create()

onStart()

on Resume()
user navigates
to the activity

Activity
App process running
killed

Another activity comes


into the foreground User returns
to the activity
I
Apps with higher priority onP{use()
need memory
The activity is
no longer visible User navigates
to the activity

onStop()

The activity is finishing or


being destroyed by the system

on Destroy()

Activity
shutdown

Fig. 2.1.1
fl1 Fragments in Android
• Fragment class in Android is used to build dynamic User Interfaces. Fragme nl
shoul d be used within the Activity .
• A greatest advantage of fragments is that it simplifies the task of creating UI for
mul tip le screen sizes . A activity can contain any number of fragments.
• A Fragment rep resents a behavior or a portion of user interface in a
FragmentActi vity .
• Multiple fragments can be combined in a single activity to build a multi -pane VI
and reuse a fragment in multiple activities.

TECHNICAL PUBLICA T/ONs® - An up thrust for knowledge


Activities ana "Cll:f"'' · · - ·
2-5
. ffon oeveJopment
APp1,cs •
. ·ty which has its
ent can be considered as a modular section of an actiVl ' ve
A fragtn . . d hich ou can add or remo
• lifecycle, receives its own input events, an w Y in
own f k " b ti. .ty" that you can reuse
. the activity is running (sort o Ii e a su ac v1
\\ThiJe "
different activities). .
ust always be hosted in an activity and the fragment's lifecycle
A fragtnent m · · ty is
' Jirec!1 affected by the host activity's lifecycle. For example, when the actiVl
__Iso are all fragments in it, and when the activity is destroyed, so are all
paUSt'V-1 _
fragments.
e an activity is running (it is in the resumed lifecycle state), you can
However, Whil
• anipulate each fragment independently, such as add or remove them. When you
~ rm such a fragment transaction, you can also add it to a back stack that's
managed by the activity-each b.ack stack entry in the activity is a record of the
fragment transaction that occurred.
, The back stack allows the user to reverse a fragment transaction (navigate
bacbvards) , by pressing the Back button.
• When you add a fragment as a part of your activity layout, it lives in a
ViewGroup inside the activity's view hierarchy and the fragment defines its own
view layout. You can insert a fragment into your activity layout by declaring the
fragment in the activity's layout file, as a <fragment> element, or from your
application code by adding it to an existing ViewGroup.

Importance of Fragments

• There are many use cases for fragments but the most common use cases include :
1
~=ing View and Logic Components - Fragments enable re-use of parts of
Y screen mcluding views and event logic over and over m· cliff
eren t ways
across many dispar a te acti vi.ti"es. For example, using the same list
dilie~ t da across
en ta sources within an app.

2. Tablet Support - Often 'thin


substantial} . wi apps, the tablet version of an activity has a
y different layout from the phone version which is diff
the 1V ve · erent from
rsion. Fragments enab le devic pecifi. · ••
elements hi1e e-s c activities to reuse shared
w also having differences.
3. Screen O . .
nentation - Often within h .
a SUbstantiall . apps, t e portrait version of an activity h
b th y different layout from the landsc . as
o Orientationst ape version. Fragments enabl
'----- o reuse shared elements while also having cliff e
erences.
. eve/opment
Mobile ApplicationD
. .
ragments . ·ty which has its own lifecycle.It
-.eel ose of F f an AdiVl ,
fSSil purp 1 section o . n,inning and can also be reusedc¾.
t is a modu ar . Activity is
• A fragtnen oved while an
dded or rein
be a . ·tt·es
.1:a nt act1v1 · t ou have to subclass the Fragment
.
class. ~o
wuere T eate a Fragmen y trUctor because Android will oftenu
und: 0 er 011ment cons '
• Backgt0 'd a public no-are,-- d d (-> state restore).
have to prov1 e t class when nee e
re-mstantiatea Fragtnen
Purpose of a Fragment ent is to support a more dyn~c UI (table~,
ain purpo se of a Fragm f U1 components a lot easier.
• The m ake the reuse o
smartphones)and also tom . U1 as an invisible worker for the
an also exist witho ut its own
• A Fragment C
Activity. . . . . . When the Activity is paused,so
• A Fragment is closely tied to the Ac~~1ty.it ~s :~ ed so are
are all fragments in it; When the Activity is es y , all fragments in it.

·~
fJjj communication between Fragments and Activity
t 1. Fragment.getActivityOmethod can return a Fragm tA tivity object.
en c This
object is just the Fragment belongs Activity.
2. FragmentActivity.getSupportFragmentManager()meth
r od will return a
android.support.v4.app.Fragment
Manager instance.
I 3. FragmentManager.findFragmentByld()method can retrieve the desired
f Fragment object with specified id.
r 4. Call Fragment.getView().findViewByld()method to get the view
controls in
that Fragment.
5. Then you can change the view control's property and add event
listener.
flJ Life Cycle of Fragment

• Android Fragment is the part of activity, it is also known


as sub-activity. Ther j
can be more than one fragment in an activity. Fragments repre
sent multiple screen
inside one activity.
• Android fragment lifecycle is affected by activity lifecycle
r included in activity.
because fragments are

• Each fragment has its own life cycle methods that is affec
ted by activity life cycle
because fragments are embedded in activity.

TECHNICAL PUBLICATIONS®- An up thrust for knowledge


. ;on Development 2-7 Activitiesand Fragemenh
,r,ent
()BVIJ/OP
,.rcsti0f1
Mobi/8 APY-'

onCreatView()

onActlvltyCreated()

onStsrt()

onResume()

FragmentIs active

user navigates The fragment is


backword or added to the back
fragment is stack them
removed/replaced removed/replaced

f onPause()

The fragment

t onStop()
returns to the
layout back
stack
r
onDestroyview()

onDestroy()

onDetach()

Fragmentis destroyed

Fig. 2.3.1 Android fragment llfe cycle


------------ ---------------- __-/
TECHNICAL PUBLICATIONS® - An up
-
thrust for knowledge
/l;-l1w
~!f APr

la cing Fragment
ReP
add.ing one , bu t requi,res .
rocedure to. replace a fragment is similar to the
n,e P
' ceO method instead of addO.
rep 1a
men t tran sact ions is per fo~ ed, suc h as replace or remove one , it's ~ften
' W}le n frag
rd and "undo" the change.
appropriate to allow the user to navigate backwa
t transa· cti' ons, you
allo w the use r to navigate backward through the fragmen
, To FragmmtTransaction.
must call addToBackStack{)before you commit the
add the transaction to the back stack,
, When you remove or replace a fragment and
t that is rem ove d is stop ped (no t des troy ed) . If the user navigates back
the frag men
not add the transaction to the back
to restore the fragment, it restarts. lf you do
oved or replaced.
stack, then the fragment is destroyed when rem
:
Example of replacing one fragment with ano ther
KOTLINJAVA
clfy:1ngthe article tt should show
Create fragment and give .it an argument spe
, ewFragm~nt :::! ArticleFragmentO
,' :-cije args ;; Bundle()
gs:ptitJnt(ArticleFragment~G _POSITION ,
position)
,:wFragnient.ai:guments= args
. ',/ ·. ·, ·, •: •:.-, ·.

sactionQ.apply {
:: ~~sa~ion7 supportFragmentManager .beginTran ment ,
:;~;~~Hl~9~ ir~, t~yer is in
the fragment _container view with this frag
back stack so the user can navigate bac k
:/2'~~ ~~§. the ttan.~actionto the new
~J)la9e(Rl1cIJfr.agtµ.ent container, Fragment)
::;.~t···/~..·iB~
0 t~i<P-~>1•: · . . , .>··;>ti
rrcr•· ·. •.•·•· •· . : : f i:>FP

,1a1 11l l. ...... .. . . . .


• The addToBackStack()method takes an option
Itillil?/t;;CM01"'.\;b,· . ::::c·J;t,::,,;;{!cf.
al string parameter that specifies a
isn't needed unless you plan to
unique name for the transaction. The name
perform advanced fragment operations using the
FragmentManager.BackStackEntry APls.

Intent
th
. Android applications. This
• Androi·ct application components can connect to O er
t d by an Intent obJect.
connecti•on is based on a task description represen e
lication components to request
• Inte asynchronous messages which allo w app
nts are
functionalityfrom other Android components. d intents are mainly useful to
• Inte . an
nts are the objects of android. Intent type
. gs.
Perform f o1low.ing thin
® thrust for 1<now/edge
TECHNICAL PUBLICATIONS - An up
, ,v.,.,,11,c,sand
Frag
ems,,,
\

. ton oeve/oPment onents from the same app1·ications '


•th comp
th applications. For examp1e, an acti as. w(
. APP1,cs1
Mobile mteract w1
w ou to . ted by o er V1~c
• Intents allo :ents contr1bu . a icture.
as with co.rrtPOal activity for ta.king .,.--~ ---•,W•''•""'•'•'"': '·'···---···•·W••:-·'•,','N.'.',•'•""'·····• •,•··"•M,......,.,...,,..w.,•:· ,.,.,..,....,,...,_,w,....., ..-.v.,,,,,,,,,N,,.,.,,,.,,.~
vtetll "'"""·--•""~"''''"'·'''' ' .' ' jJ. ' , •.
tart an e~ ..,. ..,,..""'''""':· · ·· · · ·. Desctipuon ·
. .,., .w:"~~~;~1i~i~,,11 r· ~-': ··.· .- · . .·...................·. . . . . .:. .. .. . .... .' . . ·. . . . .:. }. . . . . .- .:·. . . ... . . . . .... . .. . . ... .. . .. .
ifil":_,;~,~-· ]::." ,. ' '
I. ' '}·~t~ :~~~:l ~t\~~t!t~;r-·•·": ,. ·":"'.·•'""·•:•":""'"":"t~ternet·object to t¢mA:dtivitv{Jm~tb~d :~e .can Start
,,~,,--• ' '?$:'~ '§:~=$..~:::~,

i """''''' "'" 11'/\1}\::,,\,t> ',, ,,, ' ' Bv nassmg, an J;ll, • ~ft · ';:A'-"fi·11r.1·hi:.l'h nerfotm.reqmr&t thiiias·. a
;,...Startir~fai).~
,,,.,,,ac~rt;t
',.-,,.;w.,~.J\
~· •.,<·>·, ·. itew • ·ru, ,,.,.·eXlS™=
r r,:AcfiVJ.v ~" a ... , , tJ,:: :.~v, r:=, • .. . · o ·
V+-• . . . ___ · l'? ...... :.... ··--· ._....... -· .,...:. •:... -·:··......-...,-:.,.· .. ,-...... ,,,. , w, : ,. ..,..;......,_, ...........

/ -· - .:1:!:~~:,:\\.~)-~::-..~-;.:~- -:- - - - :. . :- - :- - - - - -·- - - - - - ;~~~et·~ffi~ct to startS~fflc,ei>·~ethaa we -t:~start


~- ,.......:. . . . ,._., . , ~i; ··-. , ,i By pa~g an. · .· ea msttuetitm$.to· an ·existingService. a
: Statfi11g se ·, new -· · ...!~.
1• • . ~I:~ ...-:. . ... . . .. . :.:. . .:. .:•:. . . . ,:•:'·'. . . . . .:. . . . . . .:. . ,. .:. . ., ,.. ·
i ' ' .'... '' .,,,,,..'" ....,. . . . ......... . ...:•·•~"''.. an Intemet.·ohmct·to sendS,tC>:ad.c.astq~ethod we can
, INliverjpga·bro.ad~~e : . By .P~ssmg · to t;ffieit agp ·b.roadcase.re.c~vers. . · , ·
: '. ' : deli.tr.~~»~~--~~!~~~~.:...,.....,,..,.,..,. ..,,.,...,. ,,,,,...,,,,.,,,,..,,.,.,Hu,,.,_
••,, , .,.... ... , •••, w•~-'· ·· e
~~-H••,.,~W"'"~·--~ b.. ,iect which is used to request an action from another
.,,,...,..,,.."""'"' "'~---.. ~-----·•· --'· . • f,
• Intent IS a messaging o J • •
component such as activities, services, broadcast re~e1~ers and content provider!.
Your code can send them to the Android system defmmg the components you ar1
targeting. For example, via the startActivity() method you can define that ilii
intent should be used to start an activity.
• An intent can contain data via a Bundle. This data can be used by the receivini
component.
• In Android the reuse of other application components is a concept known as task
An application can access other Android components to achieve a task. For
example, from a component of your application you can trigger another
component in the Android system, which manages photos, even if this componenl
is not part of your application. In this component you select a photo and return to
your application to use the selected photo.

fD Intent to Start Another Activity


• An Intent is an object that provides runtime binding between separa~
components, such as two activities.
The Intent
• wid . represents an app 's intent
. to do something. An intent can be used for 2 •
e v anety of tasks, one of th ese task is use of . intent to start another activity.
• In MainActivity add th E
as shown : ' e XTRA_MESSAGE constant and the sendMessage() code ft.

00~1; Val
· EXTRA
· • _MESS
. .. . .AGE. = corn.examplt.l.myfir8tapp.MESSAGE'
II
r»_ •
.. ' . •-.::,;

,clas.s Mai~cti'Vit y : AppCoJJlpatActivity()


c · ·.S
{
· •

ovemde -'-•-
uJ.u on rttate(•avedlnst
. .
su;per.onCieate(sav edinet . .. S ance tate: Bundle?) { . •
e~tContent . . . anoe tate) .
· · · View(JllJcY9ut•.aattvity-~l . .. . .
------- ~TE;C;H;N,;C~Al~P;U~B~ll-; C~A~Tl: ON~S]®~An
-:---~==:=:::_:_:~__.-/ - up thrust for knowledge
. (ion Development 2- 11 Activitiessnd Fragements
;teAPP/fcS

Here's what's going on in sendMessage():


• The Intent constructor takes two parameters, a Context and a Class.
• The Context parameter is used first because the Activity class is a subclass of
Context.
• The Class parameter of the app component, to which the system delivers the
Intent, is, in this case, the activity to start.
• The putExtra() method adds the value of EditText to the intent. An Intent can
carry data types as key-value pairs called extras.
• Your key is a public constant EXTRA_MESSAGEbecause the next activity uses the
key to retrieve the text value . It's a good practice to define keys for intent extras
~ith your app's package name as a prefix. This ensures that the keys are unique,
incase your app interacts with other apps.
• The startActivity() method starts an instance of the DisplayMessageActivity that's
specified by the Intent. Then class can be created.

lrnplicit and Explicit Intent


• An irnplicit Intent does not name a specific component. It declares a general action
to perform. The action specifies the thing that the app wants to do.
: :ackground : The system is looking for an appropriate component to start: .
lllultiple components are compatible with the action, the system shows a dialog
so the
user can pick which app to use .

TECHNICAL PUBLICATIONS® • An up throsf for knowledge


Activitiesand F
rag&r
., ApplicationDeve/opment d · ha
Mob1 e
onent ava ilable on the ev1ce t t can han...1,
· no ap riate comp ' '-lle
• If there is pr op . dia tel y ·
ill crash 1trune .
action, your app w wants
to trigger a p
hone call, it only has to" spectfy

:- ....-.·.. .•...::....:,:...::...-.,:-.-.•,:.:-.-.-\./,:-::;.;-:,:-.-:..
·

··········-.··•.···::•,•···-••.',' •• ····

Explicit Intent
t by the fully-qualified cla
• An explicit Intent spec1.fi the componen ss name
es on en
. the common case to start
start. This is
t in the own app.
a comp

Example :
Intent startlntent = new Inten otherActivity.cla
t(myContext, An
fl1 Android Virtual Device (AVD)
r • An Android Virtual De
vice (AVD) 1s . nfi ti
characteristics of an Android a co gura on that defines t
phone, tablet, Wear OS, An d .d TV or Automou
y OS device that you want to sim ro1 ,
ulate in the Android Emula
tor. .
• An Android Virtual Devic
e (AVD) is a device configu th
Android emulator. It works wi ration that is run wi t,
th the emulator to provide
environment in which to instal a virtual device-spec:
l and run Android apps.
• An AVD contains a hardw
are profile, system image,
properties. storage area, skin, and o:1'

• The avdmanager is a comm


and line tool that allows
Android Virtual Devices (AVD you to create and Jlla!l'.
s) from the command line.
the characteris An AVD lets you deI•
tics of an Android handset,
Wear OS watch, or Andro
that you want to simulate in id TV de'
the Android Emulator .
• If you're using Android Stu
dio, then you do not need
instead create and manage A to use this tool and yot1:
VDs from the IDE.
• The avdmanager tool
is provided in the Android
highe r) and i.s locate d in an SOK Tools package (25.3.0
droid _sd :
k/tools/bin/ .
Syntax

avdmanag er [global op tionsl


command lcommand optio ns
]

TECHNICAL PUBLICATIONs
® - An up thrust for knowle
dge
2-13 Activities and Frtl(Jemen~
. tion oeve/opment
8
ite APP11c
·ng Application to Process
r,1aPP1
in the Java programming language.
, Android applications are primarily written
Android specific configuration files
. development the developer creates the
. m
ng es the app Iicati·on logic
ourtwrit
• and . th e Java programnun.g language.

ADT or the And roid stud io tool s con vert these application files, transparently
The
' to the user, into an Android application.
in their IDE, the whole Android
• When developers trigger the deployment
and started.
applicationis compiled, packaged, deployed
nversion Process from Source Code to And
roid Application
s files by the Java compiler.
, The Java source files are converted to Java clas
which converts Java class files into a
• The Android SOK contains a tool called dx
application are placed in this .dex
.dex (Dalvik Executable) file. All class files of the
file.
• During this conversion process redu
ndant information in the class files are
e Sb'ing is found in different class
optimized in the .dex file.For example, if the sam
of this Sb'ing.
files, the .dex file contains only one reference
in size than the corresponding class
• These .dex files are therefore much smaller
files.
project, e.g., the images and XML
• The .dex file and the resources of an Android
e) file. The program aapt (Android
files, are packed into an .apk (Android packag
Asset Packaging Tool) performs this step.
data to run the Android application
• The resulting .apk file contains all necessary
and can be deployed to an Android device
via the adb tool.

droid SOK Features


• Im
1 N0
P_ortant features of Android SOK are as under.
or release approval processes .
· licensing, distributions or development fees
2. Fu11 mul .
timedia hardware control.
3. APis f . meter and the compass .
or using sensor hardware including accelero
4 .
. APis for l
OCa tion based services.
5
· Android In
6. Sha ter-Process Communication (IPC).
7 red data storage.
. Backgro
8. Ji und applications and processes.
Oll1.e sere .
9. en widgets, live folders.
WebIGt-basedweb browser.

thrust for knowledge


TECHNICAL PUBLICATIONS® - An up
Mobile ApplicationDevelopment 2-14 Activities and Fragements

10. GSM, EDGE and 3G networks for telephony and data transfer.
11. The Android SDK includes development tools which helps compile and debug any
app.
\ 12. Android emulator shows how app will look and behaviour on a real Android
device.
User Int e rface

syllabus
. h the User Interface Usi.ng View
. . . .
s and ViewGroups Working . .
Working wit wzth View Groups, Building
with the AdapterView Class, Designi . . .
ng AutoTextCompleteView , Implementing Screen
dat~ t· n Designingthe views programmatically, Handlin
o,ienta 10 , g UJ events, Creating Menus.
-
Contents
3.1 Adroid Graphics Interface
3.2 Layouts in Android
3.3 Android User Interface
3.4 Event Handling
3.5 Android Toolbox of Standard View
3.6 Menus in Android
3.7 Android Layout Classes
3.8 Short Questions and Answers
3.9
......__
Multiple Choice Questions
Interface
Ill An d ro id G ra p h ic s
.
• Android graphi ca1 interfaces are ually implemented as XML fi1 (
be dy na m i ll us
de ). es although they
coul d al so Ja va co
nd ro i . ca y created from
• An A ly simi}. · to a comm
d UI Is conceptual on ........ J. lV1L page.
AT
ar
• In a manner simi}ar to a web pa . ction, when the And ro1 user touches th
.d
in te ra
ll .
screen, the contr o er interprets th .
ge
te rm in es w ha t specific portion o:
an d de
th
en an d ge st ur es were invoJ:e:put
e sc re ·
th • in f way
• Bas ed on
Is ormation it telJ s th e
o~ el ab ou t th e in teraction in such a
"m
th e ap pr op ri at e "callback liste cl e st at e co ul d be called into action.
th at . ner or lifecy
ic at i
• Unlike a W eb ap pl
on (which refr eshes its pag es af. t er explicit requests from the
roid back d ietly notify the
us ) yn ch ro no us A nd se rv 1c ~ co ul d qu
er an as e ch an f groun
hi ng a cn ven coordinat e on a
ab ou t so m uc h as re ac
controller
. ge o state . (s , d be
o&
tr ig gered ,· all of these
)
map an m tum ad ch s st at e co ul
. ange of the view
w·tI h out user intervention

m Layouts in And
roid
h Id'
contain ers used for o mg O
th er Views and
ou ts ar e in vi si ble structured
• Lay
nested layouts. d user interface and can
ure fo r an an dr oi
l la yo ut de fi ne s the visual struct up ob je cts or you can decla
re
• A ty pi ca w /V ie w G ro
te d ei th er at ru n time using Vie m l which is located
in the
be crea m ai n_ la yo ut .x
la y o u t us in g simple XML file
your
of your project.
res/layout folder as bu tt on s, labels, textboxe
s,and
ts su ch
t m ay co nt ai n any type of widge th e la yout resource from
yow
• A layo u ca n lo ad
. O nc e y o u r la yo ut has created, you im plementation as sh
am
so on reat e( ) ca ll ba ck
io n co de , in your Activity.onC
applic at
below -

Android Layout
types
A n d ro id w h ic h you will use in alma
o f L ay outs provided by
• There ar e n u m b er
fe re n t v ie w , ~ oo k and f~el. . a 5~
if
A n d ro id ap p li ca tions to ~rovi~e d th at ah gns all children m
all the w g ro u p
r L a y o u t - L in ear layout 1s a vie
1. Linea
, v er ti ca ll y o r h o rizontally. s child views'
direction v ie w g roup that display
o u t is a
ut - Relative Jay
2. Relative Layo
relative positions. e
rust for knowledg
., Anp/icstion Oe velopmem 3 _3 User Interface
f,fob1,e ,.,
;..----
view that .
Table Layout - Table layout is a gro ups views into rows and columns ·
3. .
bles
Ab sol ute Layout - Absolute layout ena you to spe cif y the exact location of its
4· children.
Id
. Fra me La you t - The frame layout is a placeh 0 er on screen that you can use to
5 display a single view.
.
. of scrollable item
t Vie w - Lis t vie w is a vie w gro up that di"spl ays a 1ist s.
6. Lis
.
. 1ays item . nal,
. a two-du. nens1o
Vie w - Gr id vie w is a vie w Gr oup that d 1sp s m
7 Grid
• .
scrollable gnd.

IIJ Android User Interface


del y use d OS ma de for sm art phones and tablets. It is an open
• Android is a wi
jec t led by Go ogl e and it is rel eased under Apache License.
source pro
y lar ge com mu nit y tha t ext end its features and creates apps that
• Android has a ver
cover almost all aspects.
p
lica tio ns, cal led app s, are bui lt on Android UI framework. Ap
• All android app
firs t thi ng a use r see s and interacts with. From the user
interface is the ry app
thi s fra me wo rk kee ps the ove rall experience consistent for eve
perspective, developer
in ou r sm art ph on e or tab lets . At the same time, from the
installed d to build
e, thi s fra me wo rk pro vid es some basic blocks that can be use
perspectiv
ace (API).
complex and consistent user interf
An dro id VI int erf ace is div ide d in three different areas :

I. Home screen
2. All apps
Recent screen
3.
the "la ndi ng " are a wh en we power our phone on. This
• The home screen is
iza ble and the me d. Us ing widgets we can create and
interface is highly custom
personalize our "home" screen .
wh ere the app ins tall ed are displayed , wh ile recent
• All apps is the int erface
ps.
screens are the list of las t use d ap
·d ch an ge d a lot in ter ms of its featur es an d its interfaces .
• SUlCf' l·ts·, · b·Om, An dr 0 1 na e ·
L-,. .
eaJing
of the sm art ph on e po we r ma de possible creating ev er mo re app
The grow-th
apps. er fac e and we ll
. ·d d 1'd not have a consis ten. t int
· d .
• At J beg1nn 1ng, apps 1n An ro1
·t _
-1·,,n .
u.on struc tur e and
ic
d1•.fferent approach, nav1ga. . .
so ev ery ap p h ad a · ·
of th~ mo st tmportant
d_efmed rul e5 f sion and it wc1s on e
bu ttoN po~ition . This caused use
r con u
tOS .
missing featur es co1npared to the
Editable Text View
· f Id places the cursor in the text field and automaticaJ.I
• The EditText editable text ~e d You will change attributes of the text entry fi /
displays the on-screen key oar · ti hil ed
so that the keyboard suggests spelling c~rrec ons w e you type, anct
automatically starts each new sen tenc e with capital letters.
For example :
. .1nputType="
andro1d: textCap Sen tences" : Sets the keyboard to capital letters at the
beginning of sentences .
android:inputType="textAutoCorrect" : Sets th e keyboa rd to show automatic
spelling corrections as you enter characters.
·
an d r01·d :1nputType= "textMultiLine" .• Enables the Return key on the keyboard to
end lines and create new blank lines without closing the keyboard.
android:inputType="textPassword" : Sets the characters the user enters into dots to
conceal the entered password.

ilfl Radio and Toggle Buttons

• Radio buttons are input controls that are useful for selecting only one option from
a set of options. You should use radio buttons if you want the user to see all
available options side-by-side.
• A basic Button is often used to perform some sort of action, such as submitting a
form or confirming a selection. A basic Button control can contain a text or image
label.
• A CheckBox is a button with two states-checked or unchecked. you often use
CheckBox controls to tum a feature on or off or to pick multiple items from a list.
• A ToggleButton is similar to a CheckBox, but you use it to visually show the state.
The default behavior of a toggle is like that of a power on/ off button.
• A RadioButton provides selection of an item. Groupm· g Rad· B tt
together in a container called a RadioGroup enables the dev 1 10 tu on
nf
contro 1s
th
only one RadioButton is selected at a time. e oper o e orce at

fill Creating Radio Button

• To create each radio button option, create a RadioButton .


because radio buttons are mutually exclusive, you must m your layout H
· owever,
inside a RadioGroup. By grouping them together, the syst group them together
. . em ensures th
radio button can be selected at a time. · a t o nl y one

®
TECHNICAL PUBLICATIONS - An up thrust for k
now/edge
Mobile APP"l,auv" ...,~. ~•-,-· .. -· .. user tnrerrace

11
<?,alll version= 1.0 en~oding='utf-8"?>
11

<RadioGroupxmlns:android="http://schemas.android.
cornJapk/res/android"
11
android :layout_ width= match_parent"
11
andfoid:layout _height= wrap _content 0
android:orientation="vertical">
<RadioButton android:id="@+id/radio J)~ates''
aactroid:layout _width-::;: 'wrap _conte.nt"
android:layout _ height=."wr:ap - content"
. .• ·.•. '.··.·

.android:text = @stri.ng/pir~~s;
11

public void onRadi~~tttonOtlqk~'(Vi.eiW\\l1~i,J{ \ •· ·. .


II Is the button now 'c.:1\.e.cked?·. · . • • .· · · •· .·. . ·• . .· .
boolean checked =·((Radi<>Buttori)vi~).isChe¢ked{); ·

/ I Check which radio button was clicked


switob(view.getld()) {
c.ase Rid.radio _pirates:
if (checked)
I I Pirates are tbe best
break ;
case R.id.radio_ninjas:
if (checked)

I I Ninjas rule
break.;
}

Sp~nners
• Spmne-rs provide a quick way to select one value from a set of options. Create a
spinneT ltkE a,ny view and specify the android:entries at.tribute to specify the set of
op t~ons
<Sp.inner
android :id = "@ + id/mySpinner'
andlOid :layout _width= "wrap_ content "
andrOid:ent.rles : ' @erray/plane ts _arrays" 1

aodroid:proinpt "@string/planets _p10mpt•


andfoid:layout _Jieigb.t= "wr~ _ content• />

an d then spec ify the string array of options in res/values/planets_array.x:ml:


<?xml V81'8ion= •t .01' encoding =~-8 •? >
<reeoutce.>
<8tdng-.nay name='-pl anets _array'>
<item.:> Mercury < /item>
<item>Venus</item>
<item>Earth </item>
<It.em> Mars </item>
</atmg ..array>
<I~>

m Event Handling
• lnput Events are used to capture the events, such as button clicks, edittext touch,
et;c. from the View objects that defined in user interface of our application , when
the use r interacts with it.
• To handl e input events in android, the views must have in place an even!
li• ten~r . The View class, from which all UI components are derived contains a
wide range event listener interfaces and each listener interface contains an abstract
dt-da:ratio n for a callback method .
• To rrspo nd to an event of a particular type, the view must register an a ppr opriate
ev,-..r, t hst{-ner and impl ement the corresponding callback method .
• J <..)r ttx.'.lmple, ii b utt on is to respond to a click event it mus t register tl
Vi,.w .onCUckLis tn1er even t lis tener and implement the corre spondin g onClickL
c.11Jb4L1'. me-:th od . 1n application when a bu tton click ev ent is det ected , the Androic
irAt1ir" orl 'Wi1l calJ the onO ickO method of tha t parti c ular view .

• ~ra !J~, tu handle mput events we use Event Lis teners and Event Handlin g :
and_n,.1J ar pbr-aoons to ltste,n for user mteractions and to extend a View cl.a5~, s
I
1.. . ., ri.lt'f t () t"u.dd a CuStom "'ompon.cr. T.
Android f-,yf List.ft.,.
• in Ar'u.'tr'C.iu F1·t-n t Ll.tene, a.n mtmac e in the View class that contaim a ,LJ15
b
1
i\UJo~c, rr.~-tr-"--.d f r~ metr.:od~ \<\-ill he cal.led by the Android frameworl... wht
t• l4 }, \ff.,\ •., ll ,,t 1 L" r It
. ... v t: r. : l e \._"U It\ rt, ~ U >tfl cl i.S tn.~E:F1':\.l I...
oy u.5er 1n tr-ra c t 10n
.J.. ti)
Ju• "'
n~ l 1tn t l
• Following are the call-back methods which includ d • lis .
e m event tener interface.
• There are many more event listeners available as a part f v· • •
1ass to use 1t m
·d 1· · ti
our an d ro1 app 1ca ons. o 1ew c

ES Android Toolbox of Standard View


• Android supplies a toolbox of standard Views to help you create simple interfaces.
By using these controls (and modifying or extending them as necessary), you can
simplify your development and provide consistency between applications.
• The following list highlights some of the more familiar toolbox controls :
t. TextView
• A standard read only text label. It supports multiline display, string formatting
and automatic word wrapping.
2. EditText
• An editable text entry box. It accepts multiline entry and word wrapping.
3. ListView
• A View Group that creates and manages a group of Views used to display the
items in a list. The standard ListView displays the string value of an array of
objects using a Text View for each item.
4. Spinner
• Composite control that displays a TextView and an associated ListView that lets
you select an item from a list to display in the textbox. It's made from a Text
View displaying the current selection, combined with a button that displays a
selection dialog when pressed.
5. Button
• Standard push-button
6. CheckBox
• Two-state button represented with a checked or unchecked box
7. RadioButton
• Two-state grouped buttons. Presents the user with a number of binary options of
which only one can be selected at a time.

Bl Menus in Android
"l .1 pplication functions without sacrificing valuable
• 1nenus offer a way to expose a , . d h
. . . ify 1.ts own activity menu that s d1splaye w en
screen space. Each activity can spec
the device's menu button is pressed.
h t can be assigned to any View within an
• Android also supports context menus t a h ld the middle D-pad
. tri ered when a user o s
Activity. A View's context menu 1s · gg
Mobile Applicsfion veve10µ1,,~,11 • 1//(8"'

ckb ll or Iongpresses the touch screen for around


button, depresses the tra a
3 seconds when the View has focus.
. . d
• Acttv 1ty an con xt menus support submenus, checkboxes, radio buttons, shortc
te
keys and icons.
• I O improve the usability of application menus, Android features a three-sta
menu system optimized for small screens :
L The Icon Menu
• This compact menu appears along the bottom of the screen when the Menu butti
is pressed. It displays the icons and text for up to six Menu Items (or submenus)

..- . .-:-...... ··-:::::-:·:·::~;:·:::····

•iit\?I/1::r:it\:l:i{t!i\t:r;ii
Submenu '.{~~;i:!f!ihi:1,t Menu Item 2
Menu Item 3 Menu Item 4 More

• This icon menu does not display checkboxes, radio buttons or the shortcut ke~
for Menu Items, so it's generally good practice not to assign checkboxes or rad
buttons to icon menu items, as they will not be available. If more than six Mer
It.ems have been defined, a More item is included that, when selected, displays tl
expanded menu . Pressing the Back button closes the icon menu.
2. The Expanded Menu
• The expande d menu is triggered when a user selects the More Menu Item fro:
the icon menu. The expanded menu displays a scrollable list of only the Mer
Items that weren' t visi ble in the icon menu. This menu displays full text, shortC'
k.e)rs and checkboxes / radio buttons as appropriate.

Menu Item 5

Menu Item 6

Manu item 9

0 Ched(8ox
3. su
broenus
hierarchical tr ee " can be awk d
The traditio.na, l !'expanding . eta h . wa r to navigate using a
• e th at th is m ! ill
mouse, so 1t s no surpris p or is particular Y -suited for use on
mobile devices.
.
dr oi d alt er na tiv e is to display e ach sub menu m a fl . g window. For
• The An enu ch oatin
n a us er se lec ts a su bm as th e cr ea tiv ely 1b 1d
example, whe . . su
flo ati n . a e e Submenu
ed in a n .
from menus, its items ar
e di sp lay g menu Dialog box, as show m
. 361
F1g. . . .
* Subrnenu

Menu item 1
Menu+b

I·/ )Check box


0 Radio 1

(v.Radio2

0 Radio3

Fig. 3.6.1

ID Android Layout Classes


of the ViewGroup
ore generally, "layouts") are extensions
• Layout Managers (m en.
the position of child controls on a scre
class designed to control pl ex interfaces using a
cr ea te ar bi tra ril y co m
d, letting you
• Layouts can be neste
anagers.
combination of Layout M It's
m e sim pl e lay ou ts to he lp you construct your UI.
des so
• The Android SOK inclu n of lay ou ts to make your interface
easy to
ht co m bi na tio
up to you to select the rig
understan d and use. lay out classes available :
th e m or e ve rsa til e
des some of
• The following list inclu
1. FrllDel.yout ch child
M an ag er s, th e Fr am e Layout simply pins ~a
Layout
• The simplest of the le ch ild re n sta ck s ea ch new child on top
er . Adding multip
vie w to the top left com
us , w ith ea ch ne w Vi ew obscuring the last.
of the previo
1. A.46- \CIJ'yyOU t
I:_ lly or
Vi ew in a str aight Une, either verti ca
• A Lmea r La yout a.d ·
d s each ch ild
. d V. r row while a horizontal
ho · s on e ch 1l le W pe '
ca l lay ou t ha
nLontaJ Jy. A ve rti
of Vie w s .
layout has a single row
3- 10
Mobile ApplicationDevelopment
LI~
. Layout Manager allows you to specify a ''wei h ,,
• The Lmear . f h . hin th . g t for M
1 the relative size o eac wit e available s each ch
that contro s Pace. I

3 RelativeLayout .
· . th Relative Layout, you can define the positions of ea h
• Usmg e c of the .
. tt·ve to each other and the screen boundaries . chi!o.
• Views re1a
4. TableLayout
• The Table Layout lets you lay out Views using a grid of rows and col
can span multiple rows and columns and columns can be set to sh.:_,llllini11
'UUU( or ~0
s. AbsoluteLayout (

• In an Absolu": Lay~ut, each child View's position is defined in ~


coordinates• Usmg this class, you can guarantee the exact · layout •,1
components, but at a price. Compared to the previous managers, d~
layout in absolute terms means that your layout can't dynamicallya~
different screen resolutions and orientations.

Working with Layouts


• Much as web designers use HTML, user interface designers can use XML1oi
Android application screen elements and layout.
• A layout XML resource is where many different resources come togetherro·
the definition of an Android application screen.
• Layout resource files are included in the /res/layout/ directory and are(~
into the application package at build time. Layout files might includen'il
. t £
m er ace controls and define the layout for an entire screen or describeC
controls used in other layouts.
Storing the Data
4 Persistently

Syllabus . . . .
. the Data Storage Opti ons, Uszng the internalstorage, uszngthe externalstorage, using the
JnJroducing . .
e Work ing with conte nt provider.
sQLileDatabas ,
-Contents
4. 1
storage Data Folder
al Storage
4_2 Using /ntem
Storage
4_3 Using External
4_4 Shared Preferences
4.5 SQUte
4.6 Content Provider
4. 7 HandlingDatabase in Android
4.8 Short Questionsand Answers
4.9 Multiple Choice Questions
~M~ob~il~e!_A~pp~l~
I ic~tat~io~n_: 4 _2
D~ e~ve~o~p~m~e~n~-----~-=-----Sto ring the Data PersistenN"
-------------.!_
Bl Storage Data Folder
Store application-specific data
• The application data folder is a
special hidden folder that your app
store application-specific data, such can use to
as configuration files.
• The application data folder is aut
omatically created when you attemp
file in it. Use this folder to store any t to create a
files that the user shouldn't directly
with. interact
• This folder is only accessible by
your application and its contents are
the user and from other Drive apps. hidden from
• The application data folder is del
eted when a user uninstalls your
MyDrive. Users can also delete you app from their
r app's data folder manually.
Ill• Application Data Folder Scope

• Before you can access the applica


tion data folder, you must reques
https:/ /www.googleapis.com/ auth/ t access to the
drive.appdata scope. For more
about scopes and how to request acc information
ess to them, refer to Authenticate
your users.
lifj Creating File in App Data Folde
r
• To create a file in the application
data folder, specify appDataFolder
property of the file and use the file in the parents
s.create method to upload the file
to the folder.
• The following example shows
how to insert a file into a folder
library : using a client

File fileMetadata = new FileQ;


fileMetadata.setN ame("config .json 9
);

fileMetadata .setPa:rents(Collections.
. . . singletont· t(ii . D
Java.10.FilefilePath = new Jav . lS app ataFolder'))· · ·
a io File('1.Q1-s/ . nfi ·. .
FileContent mediaContent = new · · · co g.J son")· · '
FileC t (u .. '
File file = driveService .files().create on ant applica tion/ ' .. fi p
(fileMetad . . Json , le ath):
.setFields(' 1id11 )
ata, mediaContent)
.execute();
Syf;te,n.out ,p.rintlnC'File ID: " + file .getld());
(Iii Search for Files in App Data Fo
lder
• To search for files i.n ithe
application data
appDataFolder and use the files.li folder, set 1-1...e
st m e thod . '-HJ spaces field to
4 3 ______ _:S::to:..'.ri~ng~t~he~D~a~ta~P,~e~rs~is~te~n'!!!_tly
__
n_t __ __ _ _-__
~s::t1.:.·on_D_e_v_el_op_m_e_

le sho ws how to sea rch for file s in the application data folder
, The following examp
using a client library :
. ···.,;
, ~~miilite,..-....:.tanv~seivi6e-:tiiestJ:n~ y, . ~-· .. .,:
·:satiJi~~s(~a,ppDat~ol~erlr- ,·. . .

lfJ Using Internal Storage


al File-
Android Read Write Data To Intern storage(SD
internal storage (ROM) , external
• Android data can be saved in
se.
shared preferences or SQLite databa
roid file system is Linux based als
o.
• Android is based on Linux, and
nitor and
id stu dio pro vid e and roi d dev ice monitor tool for you to mo
• Andro
and your PC.
transfer files between android device
e
inte rna l dat a file s is sav ed in /data/data/ <your app packag
• All android app saved in
fol der like bel ow . For exa mp le, my app data internal file is
name>
I data/ data/ com.dev2qa.example folder.
.
der under the package name folder
• There are files and cache sub fol rn this
es fol der • and roi d.c ont ent .Co nte xt's getFilesDir() method can retu
l. Fil
general files.
folder. This folder is used to save
- and roi d .co nte nt.C ont ext 's get Ca cheDir()method can return this
2. Cache folder
cached files.
folder. This folder is used to save ro id
ice inte rna l sto rag e spa ce is low , cache files will be removed by and
• When dev
ke inte rna l sto rag e spa ce bigger . Generally you need to
os automatically to ma
not
sed cac he file s in cod e tim ely , totally cache file size is better
delete the unu
more than l MB .
QJ Uaing External Storage
Android ext.mar Storage ,
ROM ) , extern.al stoTage(SD card)
• Android data can be saved in interna l storag e (
.
shared preferences ot SQLlte d atabase d _,.
ulg\Uatwn
-L ld externa l storage can be used to \svr and sav e dat a, rea cor
• AnUJ'O ite
falh l'k .
t •I.. I

o stor e app lica tion c d ta, u tere s no


I f \,,f'- .J E>torage such as SD car d ca n al.s
.,,.~rna __ _ _
d upo n file ~ you sav e to the e.xtema.1 s tor age_. ____
------ ~~orce
----- - -
--:..
______ "'_:_-_ ..,..:________________
~M~ob~ile~A~p~p~lic~a~tio~n_:D~e~ve~lo~pm~en~t

• In general there are two types of External Storage :


1. Primary External Storage: In built shared storage which is
"ac~essible by the
· a USB cable and mounting it as a drive on a host
user by p1uggmg

computer". Example: When we say Nexus 5 32 GB.


2. Secondary External Storage : Removable storage. Example : SD Card
• All applications can read and write files placed on the external
storage and the
can
user can remove them. We need to check if the SD card is available and if we
we
write to it. Once we've checked that the external storage is available only then
can write to it else the save button would be disabled.
and
• Firstly, we need to make sure that the application has permission to read
add
write data to the users SD card, so lets open up the AndroidManifest.xmland
the following permissions :

• Also, external storage may be tied up by the user having mounted


it as a USE
is no!
storage device. So we need to check if the external storage is available and
read only.
extern~
getExternalStorageState()is a static method of Environment to determine if
false we've
storage is presently available or not. As you can see if the condition is
disabled the save button.
1. Environment.getExternalStorageState() : returns path to internal SD mount point like
"/mnt/sdcard".
2. getExterna/FilesDir(): It returns the path to files folder inside
And~oid/~ata/data/application_package/ on the SD card. It is used to store any
reqwred_ files. for your app (like images downloaded from web or cache files).
Ono
the app 1s urunstalled, any data stored in this folder is gone too.

IIJ Shared Preferences


. dal
. .ive
allow you to read and wr·t1 e small amounts of pnnut
• Shared preferences.
(as key /value pairs) to a file on the device storage.
. .
• The SharedPreference class prov·1d APIs for gettin g a handl e to a prefer ence W
and for read• .. es
mg, wntin g, and manag ing this data.
• The shared preferences file itself is
accessible to (shared with) all th managed by the Android framework, ~ 0
howev er, share d w·th . e comp onent s of your app. That data tS
1 or accessible to any other ap ps.
./;cation Development 4 _5
-
----------~~
!tfobileAPP~:_..- -----~ St~orlnr,ng the Data P .
. ~~ ers,stentty
e data you save to shared prefer ences is differ
• Th ent from the data m .
activity state. the saved
.
The data in the activity instance stat e is retained across activity instan .
• ces m the
same user session.
user sessio . ns e
Shared preferences persist across if
· your app is killed and
• dev ice is reb oot ed. ' ven
restart ed or if the
you d
, use shared preferenc.es only when larg er
nee to save a small amount data as
simple key / v al ue pairs. To manage am ounts of persiS!ent app data use the
suc h as SQ L dat aba ses .
other methods

eferences
- Creating Private and Shared Pr

, Individual activities . can have their own privat e pre f erences. These preferences are
. th ...
for the .sp eci fi c Ac tivi ty only and are not shared WI·th o er actiVIties within the
appIicati on.
of private preferences.
• The activity gets only one group
activity's private preferences :
• The following code retrieves the

.:i11!1: ii!!~1W!:JA~);
red pre fer enc es by nam e fro m any activity in the application .
• You can access sha
it to the num ber of dif fer ent shared preferences you can create .
There is no lim
e sha red pre fer enc es cal led Us erNetworkPreferences and another
You can have som
called AppDispla y Preferences.
• How you organize shared prefer
ences is up to you, the developer .
variable (in a base class
r preference nam e as a
• However/ you want to declare you ulti 1 cti vi ties· For example
name across m Pe a
or ucader) so that you can reuse the
1. _

CE_FILENAME• •A,ppPTe&' ;
~llc Btatic 6-1 StriDa PREFEREN

• SQLlte ~ management
I d t b
provi·d_es a relahona a a
• ·SQ1Y~
_· tw.
is a sof tv.1a1e library that
S\ 'Stem
.gh •ght in terms of setup, database administrati on
• The lite in SQLlte means li t we1 ,
and required resoq.rce.
·
• A SQLlte database is a good storage so1ution w
hen you have structured data ~ t
you need to store persistently and access, sear ch , and change frequently.
• SQLlte is self-contained means 1t · · · · al support from the operating
reqwres nurum
system or external library.
• This makes SQLite usable in any environments especially in embedded devices
like iPhones, Android phones, game consoles, handheld media players, etc .
• SQLite is developed using ANSI-C. The source code is available as a big sqlite3.c
and its header file sqlite3.h.
• If you want to develop an application that uses SQLite, you just need to drop
these files into your project and compile it with your code.
• SQLlte databases are very lightweight. Unlike other database systems, there is no
configuration, installation required to start working on an SQLite database.
• :'11en you use a SQLite database, all interactions
with the database are through an
instance of the SQLiteOpenHelper class which executes your requests and manages
your database for you.

• :n,e ~droid SQLite Database requires very little memory (around 250kb), which
IS available on all android devices.

• Every device has an inbuilt support for SQLite database which . .


managed on android right from its creation, execution to q,uPrvin 18 automatically
• SQL ·te • - , ...... Lg up process.
l IS an open source database, available on eve .
supports standard relations database featur lik S ry android database. It
tate · e QL syntax tr
s ments. SQL1te is considerably, the Ii es, h . , ansactio· ns & SQL
most of the SQL commands don't run SQgLt~r version of SQL database, where
• . . on ite database.
Once SQL1te is in place it is .
availabI . . , important to ensure th t
em SQLite; only then can it b a a feature or command is
• Th B . e executed.
e as1c Advantages of SQL't .
1 It' Ii I e .
. s a ght weight database
2. Requires very little m
emory
3. An AutomaticaU
• The SQLite supports~ managed database
1. Text(like stnn ) y three Datatypes :
g - for storm
2. Integer(like int) f g data type store.
3 - or storing .
. ReaJ(Jike double) - £ . integer Prirnary key.
---- or storm~ ln .... _
CJ"tJnh"
. . c other
·•I> d ataba se m anageme n t syste h
• . ms, t ere is no C .
. and in SQLite. In SQL1te, here is how y
cornni . REATE DATABAS
ou can create a ne . :e
·rnplest way to create a new SQLitcDat b .
'{he st w database :
• se the opcnOrCreateDutaba se() method ofa aBe mstance.·
f
to O or your application .
unP°1' pdrOld,d&W>Ue,1qllteBOLiteDatabe.ae; your apphcation conte . u,
xt, hke this •
•· ·teDatabasemDe.tehase:
soL>tablle • openOrCreateDatabase(
tnD• · tab81 e·db" ,
~ y ,qU.te_da .
sQLiieDatabase.CREATE_IF_NECESSARY;
null):
ED content Provider
• A content provider manages access to a central
. . . . repository of d t A . .
art of an And roid appl a a. provider IS
P icati on, which often provides its own UI f
the data. or wor king with
.

• Content providers are primarily intended to be used


by other applications, which
access the provider using a provider client object.
• Together, providers and provider clients offer a
consistent, standard interface to
data that also handles inter-process communication and
secure data access.
• A content provider presents data to external appl
ications as one or more tables
that are similar to the tables found in a relational database.
• A row represents an instance of some type of
data the provider collects, and each
column in the row represents an individual piece of
data collected for an instance.
• Typically you work with content providers in one of
two scenarios; you may want
to implement code to access an existing cont
ent provider in another .
• A content provider coordinates access to the data
storage layer in your application
for a numb er of di fferent APls and component s as
illustrated in Fig. 4.6.1.
• The content prov ider and other components include :
l . Sharing access to your application dat a with other
app lications
2. Sending data to a wid get
3. Rt tu rnin~ custom search suggestions for your appl
ication throug h the
search frameworlic using SearchRecentSuggestionsProvide
r .
4. '-.~1tchruni1ing application da ta with your L~ing an
server
1rnpl~men tanon of Abs.
tract Threa ded.SyncAdapter

-- s Loadu ,tS da ta m your Ul ui m g a Cur&orLoader

1[GHNICAI PIJBLJCA. TIONS~ · All up f/)11.1-'1 fOf N~


-~
AbstractThreadedSyncAdapter Cursorloader

Widgets

Other applications
ContentProvider

Search

Data storage Data storage

Fig. 4.6.1

Content Provider Classes

• A content provider in Android shares data between applications. Each applicatior,


usually runs in its own process.
• By default, applications can't access the data and files of other applications.
• You can make preferences and files available across application boundaries Wifr
the correct permissions and if each application knows the context and path.
• This solution applies only to related applications that already know details abo~
one another.
• In contrast, with a content provider you can publish and expose a particular datt
type for other applications to query, add, update, and delete, and thOi
applications don't need to have any prior knowledge of paths, resources, or wrr
provides the content.
• The canonical content provider in Android is the contacts list, which provide
names, addresses, and phone numbers.
• You can access this data from any application by using the correct URI and
series of methods provided by the Activity and ContentResolver classes to retrie1
and store data.

(1:fj Deleting Database Records


1
• The data modification clauses in SQLlte are INSERT, UPDATE, and DELf
statements. It is used for inserting new rows, updating existing values, or delet!r
rows from the database .

TECHNICAL PUBLICATIONS®- An up thrust for knowledge


Y' pficat1on
. :.:::_:__~--- - ---- -=------- · oevetopment 4-9
t
,iotJileAP, Storing the D
rrr
a a Persistently
· remove records from the datab
you can ase using the rem0 ()
• () method takes few argume nts. ve method.The
reIJ'love
. g null to the WHERE clause deletes all records within th
, passin .
. le, this all records within the e table. For

~r:Z:~~=~, ;~:;:;~·::::: ~~;==


authors.~{:n.1/dl\.rl--..;t1t~,,,:.c =>.'-..:)1/f;'..J%L'K:,!'' n;;·;,;,.., ~e called thl authors .
eX~~~~"'Ki/4.h....ii-l >

k=
1

The following function takes a parameter book.Id and


, th . .d deletes the record
rresponding to at uruque I (primary key) within the t bl

, You need not use the primary key (id) to delete records; the wm~··":~::::·:
entirely up to you. For instance, the following function deletes all book records in
the table.

·a .r ···--'
. . . . •. . . ·-· .,. . . .• . .•...•...... . -. -·-·-·-•...... .. . . . . ·~-·-·.·.•.•-. ·•.:::.:.-.:.,.•:.::-:_ ·-·-•.............·.. ·..· ;
·.. ·=:-:•:.:::::;: • • :,:,:,:,'.·',·.·:.•'·':
.
:::: /::::: =:=~·== :=::~:=::-\:it\\-:::.~:=:=:::.::::J:::=:::::://J?:AiJ@( MJ:f/f?f. ...:::)?\:\(\; :\t{=/\{/t://}(~ :)/:i/r····· ./
...•.,·,. ·.··.•.·•.,.··.·
'·'.'·.'·.'.·•,·, ...·,'·,.'.,.·,·.·.,'. ..',:.,:,:••
.·.=.,·.:.:.· ..:,..·,:,'•.:.,,·,.::,:.·::...,•:.,.','..','....
• ,',·
.'.:.·.'· :.·.·.'•.:.',. ·,' ,:.,,·,,·,:.,.'.,'.:
' ·:'.:,·. .:,:,:;:,::::::::,•:.:,:::::::c:::::::·::,:;: :•:•:::·::=::::::,:,;:::,::. . . . , ........·•·
} ... . • . . .. . :::::.::::t:=:::::::::

DJ Handling Database in Android


• In the same way that you retrieve data from a provider, you also use the
interaction between a provider client and the provider's ContentProvider to modify
data.

• You call a method of ContentResolver with arguments that are passed to the
corresponding method of ContentProvider.
• The provider and provider client automatically handle security and inter-process
communication.

QI Inserting Data
• To insert data into a provider, you call the ContentResolver .insert() meiliod. This
th3 1
method inserts a new row into the provid er and returns a content URI for
row.
Mobile Application Development 4- 10

,
•.·-:;:-: :-·.·= - __ _ ;{f. i?.. :.;:::,.::=·....:{:J;./.........
=._•••.:. •/_:_;_·;,•_/.t_:!_i._•_
' ~::-.:::;::: .... ... -.- \/..:_.-.. .. '
:(:)t;::::= '_::_>?tf:.-.:
...•. .-. .-:.. ·.-:>· :> ··::;:• :-:-·-· •.-.-:-: :_ :,.. •.
::=·:..::::- • _-_-::::···-··.:=:· ·,•::·.:-:·::·:: . ::;:/•--::_.;:=·
•,• •,• · .·..-.-.- .·.•.·.•·-··:-t=·=· ./\:::/=::):==:-. -· :·:·:-:..•:•··..
.:·::=: -i::\\i/·/ \?\:.:/:. /~\:;//:;;//\: \:. :··:;::.>;::" ·,:..;.
: hl;h;~,sintii ,
::-: <;:;:•·-~-:-: / ( \\:: :; .} /

le ContentValues obj~~:
• The data for the new row goes into a sing
in this object don't need to have llie
in form to a one-row cursor. The columns
cify a value at all, you can set a
same data type, and if you don't want to spe
column to null using ContentValues.putNull().
because this column is maintained
• The snippet doesn't add the _ID column,
value of _ID to every row that ~
automatically. The provider assigns a unique
table's primary key.
added. Providers usually use this value as the
tifies the newly-added row, with the
• The content URI returned in newUri iden
following format :
;:::::+t\:f}t:f§:\--l®n~pt;tZ.iifitin~~Pn$.XYLW<->t4@l~l.tt£v.~u'~'>: s:;:.::::1::::,::;I::Z'/,,:;":;'.Mo
;::;;;i;t:~;~{:7:',:i::::;:::::;::::~
st providers can detoo
new row.
• The <id_value> is the contents of _ID for the
perform the requested operatioo
this form of content URI automatically and then
on that particular row.
To get the value of _ID from the returned Uri
, call ContentUris.parseld().

lff j Updating Data


. h th e upd ated values jU51Th
. ect w1t
obJ
• To update a row, you use a ContentValues · · ·
• n cntena 1ust as you do with a query.
ctio
you do with an insertion, and sele
vou use is ContentResolver .update().
:.-<:::·:~.:=::/;\; .:·(·

. .;: -· -__ ~, ·· ·.. t)(}:ifirii~\~~it::.ii{>~~:\t:~t:·=:r -


·.·•.·.....•..·.•.:.,•,·· .•.•
·. .•.;· ··.•·.·.·•.··.:.·.•
:·.••.·.;.:·•,;:•.·•.·.
.. • ..·...•·.·.::....
:.:~:,··.·,.:::..•,·.:.··,·.•.·,·
.• ·•..••.... ....:...·•...·.:··•.··...
·.•.:,·:··•.:•::: • •.

• You should also sanitize user input when you call ContentResolver.update().

OIJ Deleting data


• Deleting rows is similar to retrieving row data: you specify selection criteria for
th
e rows you want to delete and the client method returns the number of deleted
rows.
• Th
r e followmg snip pe t d e 1etes rows w h ose app1'd mat ches "user " . The method
turns
e ilie number of deleted rows .
// Defines .. , . . .
va1 sel . aele.ction ontena for the rows you want to delete
vai sei::onClause :;;:: "${UserDictionary .Words.LOCALE} LIKE 7'
0
nArgs: Array<String> == arrayOf('\is et')
// D ~-
e~1es a Vari.ab!
var rowsDeL · e to contain the number of rows deleted
8 ted : Int= O

TECHNICAL PUBLICATIONS® - An up thrust for knowledge


Storing the Data Persistently
Mobile Application Development 4-12

\
• You should also sanitize user input wh
en you call ContentResolver.delete() . I

You might also like