Mad Technical Book 3161612
Mad Technical Book 3161612
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
··:.· .· -:""'.;··. ·. ·
__________ 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
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
®
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
2. Native layer
3. Application framework layer
4. Applications layer
Fig. 1.3.l illustrates android stack.
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
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
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
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.
®
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
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
·
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.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Activities
a n d F r a g m e n t s
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
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()
on Create()
onStart()
on Resume()
user navigates
to the activity
Activity
App process running
killed
onStop()
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.
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.
·~
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
• Each fragment has its own life cycle methods that is affec
ted by activity life cycle
because fragments are embedded in activity.
onCreatView()
onActlvltyCreated()
onStsrt()
onResume()
FragmentIs active
f onPause()
The fragment
t onStop()
returns to the
layout back
stack
r
onDestroyview()
onDestroy()
onDetach()
Fragmentis destroyed
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
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,,,
\
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, : ,. ..,..;......,_, ...........
00~1; Val
· EXTRA
· • _MESS
. .. . .AGE. = corn.examplt.l.myfir8tapp.MESSAGE'
II
r»_ •
.. ' . •-.::,;
:- ....-.·.. .•...::....:,:...::...-.,:-.-.•,:.:-.-.-\./,:-::;.;-:,:-.-:..
·
··········-.··•.···::•,•···-••.',' •• ····
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'
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.
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.
• 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
®
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
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
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
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"'
•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
(v.Radio2
0 Radio3
Fig. 3.6.1
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 (
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
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- ,·. . .
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.
Widgets
Other applications
ContentProvider
Search
Fig. 4.6.1
k=
1
, 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:=:::::::::
• 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().
•
• You should also sanitize user input when you call ContentResolver.update().
\
• You should also sanitize user input wh
en you call ContentResolver.delete() . I