You are on page 1of 354

Mc lc

Contents
Bi tp 1: Lm quen vi mi trng pht trin in thoi di ng .......................................................... 2
Bi tp 2: Thao tc vi Android Virtual Device v DDMS ..................................................................... 5
Bi tp 3: Cch to Android Project v tm hiu cu trc bn trong ca mt Android Project.............. 14
Bi tp 4: Cch sa mt s li thng gp trong Android Project ......................................................... 22
Bi tp 5: Tm hiu vng i ca mt ng Dng Android .................................................................... 24
Bi tp 6: Phn bit Foreground Lifetime v Visible Lifetime .............................................................. 31
Bi tp 7: Lm quen vi cc Layout trong Android ............................................................................... 40
Bi tp 8: Cc kiu lp trnh s kin trong Android ............................................................................... 51
Bi tp 9: Thc hnh v Toast Notification v Alert Dialog .................................................................. 69
Bi tp 10: S dng TextView, EditText v Button trong Android ....................................................... 72
Bi tp 11: S dng Checkbox v RadioButton trong Android ...................................................... 80
Bi tp 12: V d tng hp TextView, EditText, CheckBox, Button v ImageButton
trong Android ....................................................................................................................................... 89
Bi tp 13: Thc hnh v ListView trong Android ......................................................................... 103
Bi tp 14: Thc hnh v Custom Layout cho ListView trong Android ...................................... 125
Bi tp 15: Thc hnh v Spinner trong Android .......................................................................... 136
Bi tp 16: Kt hp Spinner vi ListView trong Android.............................................................. 139
Bi tp 17: Thc hnh v AutocompleteTextView v MultiAutocompleteTextView................. 150
Bi tp 18: Cp nht DataSource cho AutocompleteTextView lc Runtime .............................. 154
Bi tp 19: Thc hnh Gridview trong Android ............................................................................. 167
Bi tp 21: Thc hnh v Tab Selector trong Android .................................................................. 175
Bi tp 22: Thc hnh v Menu trong Android.............................................................................. 184
Bi tp 23: Thc hnh v Context Menu trong Android ............................................................... 193
Bi tp 24: Thc hnh v Intent trong Android ............................................................................. 196
Bi tp 25: Tip tc cng c kin thc Intent, v d tng hp Qun L Nhn Vin ................... 216
Bi tp 26: Dng Implicit Intent vit chng trnh gi in thoi v nhn tin SMS ........... 263
Bi tp 27: a ngn ng trong Android .......................................................................................... 274
Bi tp 28: X l tp tin trong Android ........................................................................................... 279
Bi tp 29: XML Parser trong Android ........................................................................................... 293
Bi tp 30: Thc hnh v Shared Preferences ................................................................................ 299
Bi tp 31: Cch s dng SQLite trong Android ............................................................................ 312
Bi tp 32: Tip tc cng c kin thc SQLite, v d tng hp qun l sch ............................... 320
Bi tp 33: S dng ContentProvider trong Android .................................................................... 345
Bi tp 34: a tin trnh trong Android (Multi-Threading) ......................................................... 354

Bi tp 1: Lm quen vi mi trng pht trin


in thoi di ng
Trong cc topic sp ti, Ti mun dnh nhiu thi gian hng dn cc sinh vin hc lp trnh cho
thit b di ng. C th l h iu hnh Android. Ti hi vng sau khi theo di tt c cc Topic t u
ti cui th cc sinh vin s c kh nng trin khai c ng dng trn h iu hnh Android.
y l topic u tin Ti hng dn cc bn lm quen vi mi trng pht trin in thoi di ng,
cc bn c th Comment vo topic, trao i trc tip vi Ti qua comment, qua email, qua in
thoi. ng ngn ngi.
Ni dung kin thc thc hnh:

Lm quen vi mi trng pht trin in thoi di ng

S dng Eclipse, DDMS cch thc Debug

Cch ci t Android SDK, Update Android API, Upgrade Firmware

S dng Android Virtual Device

Tm hiu cc thnh phn trong Android App

Tm hiu cc n v o lng trong Android

Tm hiu vng i ca ng dng

Tm hiu Google Play

Trong bi tp 1 ny, chng ta phi thc hin : Ci t c Java JDK, Android SDK, ADT plugin
for Eclipse, update Android SDK.
Cc bc chi tit:
Ti v ci t Java JDK: http://java.sun.com/javase/downloads/index.jsp (ci t ci ny
trc, nn chn bn mi nht)
Ti v ci t Android SDK: http://developer.android.com/sdk/index.html , ti gi ADT
Bundle for Windows, gi ny s cha cc thnh phn:

Eclipse + ADT plugin


2

Android SDK Tools


Android Platform tools
Android API mi nht
Android system image mi nht cho Emulator

Cp nht ADT plugin mi nht cho Eclipse:

1.
2.
3.
-

Vo menu Help / chn Install New Software


Nhp ng dn: https://dl-ssl.google.com/android/eclipse/ v bm nt Add gc bn phi
Chn cc thng s thch hp tin hnh cp nht.
Tin hnh Cp nht Android SDK (nu cn thit)

Tham chiu Android SDK (bt buc, nu ci gi ADT Bundle for Windows trn trang
developer.android.com th n t tham chiu cho chng ta ri).
Sau khi ci t xong y (JDK, Android SDK ), ta khi ng Elipse trong gi ADT Bundle for
windows, ta c giao din nh hnh bn di:

ng mn hnh Welcome bng cch click vo du cho k bn ch Android IDE

tham chiu ti Android SDK, ta vo menu Windows/ Preferences/ chn Android v


Browse ti SDK location m bn lu tr:

Cc bn nhn vo hnh trn, thy c Android 4.2, API 17 hin th ra. chnh l API mi nht ca
Android, ty vo danh sch API c ti v my n s hin th ra y. Hin ti trong my ca Ti ch
c 1 API 17, nu my bn c nhiu API khc th n s lit k ra y ht.
- Nu nh my tnh ca bn c kt ni internet, th bn c th cp nht API theo cch sau:
Vo menu Windows/ Android SDK Manager (hoc bm vo biu tng trn thanh toolbar), mn
hnh Android SDK Manager s hin th ra nh bn di:

Bn quan st trong mn hnh


bn trn, Nhng gi no cha c ci t th c dng ch Not installed, bn checked vo n v
nhn nt Install packages.. gc phi di cng.
Ti y l bn bit ci t JDK, ci t Android SDK, cch chy Eclipse v cp nht API.

Bi tp 2: Thao tc vi Android Virtual Device


v DDMS
Tip ni bi tp s 1 , Mc ch ca bi tp ny s gip cc bn thao tc c vi AVD (to, sa,
xa, cu hnh) v cch s dng DDMS cho vic nhn tin, gi in thoi, s dng File Explorer (
a tp tin t my tnh vo my o, v ly tp tin t my o ra my tnh.). Bit c cch kt ni
mt s thit b Android thit vi DDMS, cng nh cch thc debug.
- Ti sao s dng AVD?
+ C nhiu l do s dng AVD, cn theo Ti th n gin l n thay th cho thit b tht (Android
Emulator) nn cho d bn khng c chic Al Android no th vn lp trnh m m nh thng. Mi
s tng tc trn Emulator cng chnh l tng tc trn thit b tht
+ AVD DDMS h tr gi lp location base service vi nh dng KML nn d dng cho vic lp
trnh LBS
+ Ch c mt vi hn ch ca Emulator : Kh h tr Camera, khng h tr thit b cm ng. Nhng
bn yn tm l trn mng cng h tr th vin tng tc cm ng trong Emulator (h
tr accelerometer, compass, v temperature sensors)
1) Cch to Android emulator:
- Vo menu Windows/ chn Android Virtual Device Manager hoc click vo biu tng my o trn
thanh Toolbar:

- Ca s Android Virtual Device Manager s hin th ra nh bn di:

- to mt Android Emulator : click nt New (khoanh vng mu ):

- mn hnh bn trn, ta thit lp cc thng s: Tn my o, phn gii, API, b nh trong, b nh


ngoi (SD Card) ri nhn nt OK. Mun ln tip theo khi ng my o nhanh th ta checked vo
mcSnapshot

- Nh bn thy my o avdnew c to ra, bn ch l khi mt my o c to ra th n s


c lu tr vo user ca my tnh ang hot ng, hnh trn th lu trong
c:\Users\drthanh\.android\avd. My ca bn ci t vi user no th bn vo ng ch m xem cu
trc bn trong:

- y bn ch l nu bn cp dung lng cho SD Card ti mn hnh to my o bao nhiu th tp


tin sdcard.img s c dung lng by nhiu trong ny (do bn phi cn trng khi to SD Card i
vi my tnh c dung lng cng khim tn)
- tng t bn nhn thy tp tin snapshots.img, hin gi bn ch thy c 250kb, nhng nu nh bn
khi ng ln u tin v vo y quan st th dung lng ca n s tng ln rt ln, mc ch lu
tr li ton b thng s ln khi chy th 2 cho l
2) Chy Android emulator:
- T mn hnh Android Virtual Device Manager, ta chn tn my o cn chy ri nhn nt Start:

- Bn ch khong mt thi gian vi pht (hoc lu hn ty vo kh nng ca my). Ty vo cu


hnh m bn chn (API, phn gii), Android Emulator s xut hin nh bn di:

- Khi my o trn khi ng xong, bn vo th mc trong C: ni m lu tr my o, bn quan st


xem c nhng th mc v tp tin mi no c to ra. Sau bn tt my o ny i, tip tc quan st
bn s thy tp tin Snapshots.img m Ti cp trn s c dung lng rt ln:

3) cch s dng Android Emulator:


- Bn l mi mt my o c khi ng n s i vi mt port no , v d trong trng hp
trn l port 5554 (xem tiu ca ca s). Bn ch l port ny chnh l i din cho s in thoi
ca my o . Ta s da vo port ny thao tc : Gi tin nhn, gi in thoi. trong ca s
DDMS.
8

- Cc phm chc nng : (khng quan trng lm nn y Ti khng lit k ra, cc bn t m).
y Ti ch ni mt phm chc nng m Ti cho l ng lu tm, l phm chc nng cho php
quay ngang mn hnh in thoi. Bi v ngi s dng in thoi Smart Phone thng c thi quen
quay ngang, quay dc in thoi thao tc ci g . Ta phi lp trnh h tr cho xem ng v
ngang i vi mt ng dng c th no .
+ Bn nhn t hp phm Ctrl + F11 xoay ngang (bm li tr v nh c):

- Cch gi tin nhn gi in thoi trong my o:


+ Cch 1: Bn to thm mt my o Android khc, khi mt my th 2 c khi chy th thng
thng port ca n s l 5556, Nh bn trn Ti ni Port ny l i din cho s in thoi. My
tnh ca bn hin ti s c 2 my o Android (Bn tng tng l 2 ci in thoi tht m bn
ang cm trn tay i). Do cch m bn thao tc vi in thoi tht nh th no th vi Emulator n
s y x nh vy.
+ Cch 2: Trn thanh cng c bn quan st thy nt DDMS, nhn vo n (ch l bn phi t nht
ang chy 1 my o android)
Thng thng th trn thanh cng c s c DDMS, nhng nu nh khng thy th bn vo
menuWindows/ chn Open Perspective/ DDMS , xem hnh di:

- sau khi chn DDMS, bn vo tab Emulator Control nh hnh bn di:

- mn hnh trn:
+ Mc Incoming Number Ti nhp l 5554 (port ny chnh l s in thoi ca my o)
+ Ti chn SMS v nhp vo Hell0 Ty Map
+ Nhn nt Send
>Bn quan st my o c port 5554 s nhn c tin nhn ny:

- Cch s dng Profile Explorer:


+ Trong mn hnh DDMS, bn chn tab Profile Explorer: Trong bi tp ny bn ch cn tp cch th
1 tp tin t my tnh vo SD Card, v ko 1 tp tin t SD Card ra my tnh (Chng ta cn phi lm
vic vi n rt nhiu ln cc bi tp k tip):

10

- bn quan st th mc mnt/ sdcard . Ch l c mt vi ni cng tn sdcard, nhng bn phi


vomnt.
+ ly 1 tp tin t SD Card ra th bn chn tp tin ri nhn vo biu tng a mm bn trn
(Ti t mu vng)
+ a mt tp tin t My tnh vo SD card bn nhn vo biu tng in thoi (k bn biu tng
a mm), chn tp tin cn a, Hoc bn ko th trc tip mt tp tin no vo mn hnh ny lun.
c 2 cch u nh nhau.
4) Cch kt ni vi Thit B Android Tht
- lm c iu ny th bn phi am hiu v Driver cho mi Model in thoi. Sau khi ci
Driver y :
i vi in thoi Android s dng API 4.0 tr ln:
+ Vo Settings
+ Chn Developer Options
+ Checked vo USB debugging.

11

- Bn xem hnh bn di ( y Ti kt ni in thoi SAM SUNG SII ca Ti ti DDMS):

- Bn thao tc bnh thng: Thm tp tin vo in thoi tht, ly tp tin ra. Khi chy chng trnh
Android ta s chn in thoi Tht nu nh bn mun chy trn thit b tht. Eclipse cho php cu
hnh la chn cc loi My o, my tht khi chy ng dng.
**** Nh vy Ti hng dn cc bn xong phn thao tc vi AVD, trong bi tp k tip Ti
mun bn hiu c cch thc m mt ng dng Android khi trin khai n i theo ng no:
- V d:

12

+ Dalvik Virtual Machine l g? n c tc dng g trong ng dng?


+ Bin dch nh th no?
+ Bin dch xong th lm g?
+ Cch thc ng dng upload vo thit b
+ Cch thc ng dng c ci t vo thit b
+ Chy ng dng nh th no trong thit b
+ Lm sao tho g ng dng ra khi thit b
+ Lm sao kim tra c bao nhiu ng dng ang chy trong in thoi.
Bi tp ny Ti hi vng cc bn phi thao tc tht nhun nhuyn khi vo su bn trong lp trnh
th n gip ch cho cc bn rt nhiu.

13

Bi tp 3: Cch to Android Project v tm hiu


cu trc bn trong ca mt Android Project
bi tp s 2, bn bit cch to v s dng my o Android cng nh DDMS.
- Trong bi tp ny cc bn s thc hnh cch to Android Project v tm hiu cc thnh phn bn
trong ca n:

Cch to Android Project


Activity, Intent, View
Auto gen
Android libs
Resource
Layout, menu, values
Manifest XML

- Cng nh cch chy chng trnh Android, hiu c c ch vn hnh ca n.


1) Cch to mt Android Project:
y Ti cung cp 2 cch to Android Project:
Cch 1: Bn vo Menu File/ Chn New/ chn Android Project (xem hnh bn di):

Cch 2: Bm chut phi vo v tr bt k trong Package Explorer / Chn New / Chn Android
Project (xem hnh bn di):

Cc bn ch l khi mt Android Project c to ra th n s c lu tr trong Package Explorer.


Mt s trng hp bn khng th thy c Package Explorer (do bn l tay ng n i, hoc mt
nguyn nhn no ), nu nh cha bit cch li n ra th cc bn lm nh sau:
- Vo menu Windows/ chn Show View/ click chn Package Explorer
14

- Nu nh trong Show View m khng thy Package Explorer th bn nhn mc di cng c nhn
Other, click vo n th chc chn bn trong s c Package Explorer:

2) Nhp thng s cho mt Android Project mi:


Khi bn chn New Android Project th mt mn hnh s hin th ra nh bn di:

15

Mc Application Name: bn t tn cho ng dng m bn mong mun, trong v d ny l Ti t


SampleProject
Mc Project Name : thng thng khi bn t tn cho Application Name th mc Project Name s t
ng cp nht ging nh vy
Mc Package Name: bn nn vit thng ht v phi t nht c 1 du chm ngn cch, v d bn c
th t tranduythanh.com nhng khng th t tranduythanh.
Mc Minimum Required SDK : Chn gii hn API thp nht m ng dng c th ci t (in
thoi c API phi >= Minimum Require)
Mc Target SDK : chn API m ng dng mong mun tt nht c th thc thi trn API ny
Bn cn phn bit gia Minimum v Target:
- Ti mun gii thch s qua ch ny, trn bn thy Ti chn Minimum l API 8, v
Target l API 17. iu ny ngha l:
+ Nu nh ng dng ca Ti m c ci t trn in thoi c API 17 tc l ci ch Ti
mong mun v n s c h tr ti a cho cc c tnh bn trong ng dng ca Ti (tc
l ci tt nht)
+ Nu nh ng dng ca Ti ci trn in thoi c API l 7 th chc l khng th v y
Ti yu cu Minimum l API 8
+ Nu nh ng dng ca Ti ci trn in thoi c API >17 chng hn, th thng thng l
s c v Version mi a phn h tr version c, nhng d nhin c th khng tt bng
ng ci in thoi s dng API 17
- L do cho phn ny l bi v i vi tng API lun c mt li no , cc API mi ra i
sa v li hoc l nng cp thm mt s c tnh mi. V d nh s chc nng Nhn
Din Khun Mt c sn ca Android th bt buc phi chn Minimum API =14 v t
Android 4.0 mi h tr chc nng Nhn Din Khun Mt

- Sau khi chn cc thng s xong, bn nhn Next cho ti khi nt Finish xut hin (Ti khuyn l cc
bn c bm Next, ng c chnh sa g c v cc bn mi bt u lm quen vi n. Khi no quen ri
th Ta s quay li chi tit sau):
- Khi bm Finish th bn quan st Package Explorer xem cu trc bn trong ca ng dng
Android:
3) Tm hiu cu trc bn trong ca ng dng Android:

16

- Bn cn hiu c cu trc cy trong ng Dng Android trn:


Hy quan st MainActivity.java v activity_main.xml . Khi mt ng dng c to ra th thng
thng s c mt Activity khi chy ng dng. y bn hiu rng MainActivity.java chnh l
class cha ton b source code, cn activity_main.xml chnh l phn giao din. i vi Android khi
mt Activity to ra th thng n i km vi mt Layout giao din no (Tc l n lun c tch
thnh 2 phn: phn source code ring v phn giao din ring). Bn hiu Activity ging nh l cc
mn hnh (ca s) tng t nh l C#, mi Activity l mt mn hnh tng tc c th no .
- Bn cng cn nh rng bt k mt Activity no mun c triu gi thnh cng trong Android
Project th bt buc n phi c khai bo trong tp tin AndroidManifest.xml . Nu nh bn gi
mt Activity m Activity ny khng c khai bo trong Manifest th chc chn chng trnh s b
li v tt lun.
- Hy xem cu trc bn trong ca AndroidManifest.xml (double click vo n v chn tab nh hnh
bn di):

17

- Nh hnh bn trn bn thy , MainActivity mun c triu gi th n phi c khai bo trong


ny. V c bit nu nh mun n l mn hnh u tin c thc thi khi chy ng dng th bn phi
khai bo ging nh tag <intent-filter> trn. Nh vy nu bn mun mt Activity bt k no
c gi u tin khi chy ng dng th bn ch khai bo y chang nh vy, cn cc Activity khc bn
khng cn khai bo <intent-filter> nh trn (tc l hon ton khng c tag ny)
- Tip theo bn double click vo activity_main.xml :

- Hy quan st mn hnh trn (nhn k c 2 phn Graphical Layout v activity_main.xml. Bn


nnlm quen trong phn Graphical Layout trc):
+ Vng s 1 : chnh l ni cha cc control, layout, component bn mun s dng ci no th ko
th n vo Vng s 2. Nh bn thy th Ti va ko mt Button vo v t Id n l btnXinChao,
+ Vng s 2: l giao din, ni m bn cn thit k
+ Vng s 3: cho php thit k theo chiu ng hay chiu ngang
18

+ Vng s 4: chc nng Zoom in zoom out d thit k


+ Vng s 5: chnh l ni thit lp cc thuc tnh cho cc control c ko th vo giao din
- By gi bn vo th mc gen trong Package Explorer v m tp tin R.java ln:

Th mc gen , l thc mc cho Android t ng to ra, cho d bn c xa n th n cng li t to


ra. Ni dung bn trong bn ng c chnh sa n. Tt c nhng g bn ko th vo giao din, hay
thit lp string.xml, menu tt tn tt lin quan ti resource th n s c sinh ra bn trong R.java.
Da vo y ta c th truy sut cc i tng trong coding.
V d:
- trn bn thy class Id c cha Id ca Button m lc ny Ti ko vo giao din t tn
lbtnXinChao. Ta da vo Id ny tng tc vi control.
- Hay layout activity_main cng s t ng lu tr trong ny
- Tip tc double click vo MainActivity.java:

- Trong mn hnh trn, bn thy bn trong hm onCreate c lnh:


+ setContentView(R.Layout.activity_main) ==> thit lp giao din cho Activity.
Vi activity_main ly t R.java

19

+ findViewById(R.id.btnXinChao) ==> truy sut control l Button trn giao din.


vi btnXinChao ly t R.java
* Bn s hiu hn v cc hm ny vo cc phn sau. y mc ch l Ti ang gii thch chc nng
ca tng phn trong Android
- Tip tc bn quan st cc th mc: Drawable-hdpi, Drawable-ldpi,Drawable-mdpi, Drawablexdpi:
Bn c th t to thm mt th mc cng cp tn l Drawable, cc tp tin bn ko th trc tip vo
trong ny (to Resource). Khi chng trnh load cc ReSource s t ng vo y ly. Cn -hdpi, ldbpi, -xdpi l ty thuc vo phn gii mn hnh m chng trnh t ng vo ly ng d liu
bn trong.
- Tin hnh thc thi chng trnh:
Bm chut phi vo ng dng / chn Run As/ chn Android Application , xem kt qu:

- Ti gom li thnh 5 bc thc hin ca mt ng dng Android nh sau:


bc 1: Android Project s c t ng bin dch v chuyn qua Android Executables (.dex)
bc 2: ng gi thnh tp tin .apk
bc 3: Upload .apk vo thit b android
bc 4: Tin hnh ci t .apk
bc 5: Khi ci t thnh cng, chng trnh s c thc hin Activity c thit lp
: android.intent.action.MAIN
Mi mt ng dng Android s c thc thi trn mt my o Dalvik (khng phi my o Java). Theo
nh gii thch ca developer Android th mc ch l chy a tin trnh, gip ti u b nh.
Nh vy n y l bn bit cch to mt ng dng Android v khi ng n nh th no, ng
thi cng bit c mt s thnh phn bn trong ng dng v cng nng ca chng
Bn cn hiu r bi tp ny, Trong bi tp tip theo Ti s nu ra cc tnh hung LI ca chng
trnh v cch x l chng nh th no. V Ti chc chn rng trong qu trnh hc lp Trnh Android
bn s gp cc tnh hung m khng hiu v sao n b li, bn s b tc trong vic gii quyt li.
20

21

Bi tp 4: Cch sa mt s li thng gp trong


Android Project
bi tp 3 cc bn bit cch to v thc thi mt ng dng Android, trong bi tp ny Ti s ni
mt s cch sa li thng gp trong qu trnh thc thi mt ng dng Android:
- Bn nh l nhng li ny thng khng phi do bn gy ra m do Eclipse hoc mt s nguyn nhn
no (ta gi tm thi l Chng trnh b tng tng). Bn cng khng hiu v sao n li b li, n
khng cho php bn bin dch v thc thi ng dng mc d bn ch lm g c?
- Khi bn gp nhng trng hp kh nh vy th hy lm theo mt s cch di y (nu m vn
khng c th bn c th s dng phn mm TeamView, cung cp Id v Password Ti s login vo
my bn sa gim nu c):
Gii php 1:
- b1) Vo menu Project / chn Clean :

- b2) Mn hnh Clean hin th ln, bn chn Project b bo li v bm Ok:

- hnh trn, nu bn chn Clean All Project , eclipse s clean ton b Project trong Package
Explorer.

22

- Nu bn chn Clean Projects selected below, eclipse s clean nhng Project m bn Checked
bn di.
b3) Bn Unchecked Build Automatically v Checked li Build Automatically trong menu
Project
Gii php 2:
- Bm chut phi vo Project / chn Android Tools / chn Fix Project Properties:

Gii php 3:
- Khai bn ko th mt s tp tin, hnh nh vo Android Project n s bo li v khng th to ra gen.
Bn hy kim tra xem c phi tn cc tp tin b Vit Hoa k t u hay khng, hay tn tp tin b
khong trng hoc l c cc k t khng hp l. Bn ch cn sa li l ht li
Gii php 4:
- n gin l tt v khi ng li Eclipse.
Trong bi tp tip theo, Ti s hng dn cc bn hiu c Vng i ca mt ng dng Android
v a ra mt s li khuyn v vic lu trng thi cng nh phc hi trng thi ca ng dng.
23

Bi tp 5: Tm hiu vng i ca mt ng
Dng Android
Trong bi tp 3 v bi tp 4 bn bit cch to mt Android Project cng nh gii quyt mt s vn
gp phi khi thc hin ng dng.
Trong bi tp 5 bn cn hiu cc khi nim sau:
1) Applications l g?
2) Activities l g?
3) Activity Stack l g?
4) Tasks l g?
5) Life Cycle States l g?

1) Applications l g?
- Bn hiu nm na nh sau: Mi mt Android Project khi bn bin dch thnh cng th s c ng
gi thnh tp tin .apk, tp tin .apk c gi l mt Application (ng dng c th no V d nh
ng dng chng tin nhn rc, ng dng tm ng i ngn nht, ng dng ng k hc phn bng
sms . )
2) Activities l g?
- Thng thng trong mt ng dng (Application) s c mt hoc nhiu Activity (bn hiu i khi
l cc mn hnh tng tc ging nh Form trong .Net).
- Mi mt Activity ny s c mt vng i ring c lp hon ton vi cc Activity khc, bn s hiu
r hn v vng i trong phn Life Cycle States. Vic hiu r vng i ca Activity l rt quan trng
trong vic x l thng tin.
- Mi mt Activity mun c triu gi trong ng dng th bt buc n phi c khai bo trong
Manifest
3) Activity Stack l g?
- Tng t nh cc ngn ng lp trnh khc, Activity Stack hot ng theo c ch LIFO (LAST IN
FIRST OUT)
-Mi mt Activity mi c m ln n s bn trn Activity c, tr v Activity th bn ch cn
nhn nt Back tr v hoc vit lnh. Tuy nhin nu bn nhn nt Home ri th s khng th
dng nt Back quay li mn hnh c c.
24

- y bn ch l c 2 kiu m Activity mi :
a) M Activity mi ln lm che khut ton b Activity c (khng nhn thy Activity c): sy ra s
kinonPause ri onStop i vi Activity c
b) M Activity mi ln lm che khut mt phn Activity c (vn nhn thy Activity c): Sy ra s
kinonPause vi Activity c.
- Khi quay tr v Activity c th sau khi thc hin xong cc hm cn thit, chc chn n phi gi
hmonResume phc hi li trng thi ng dng
- Nh vy ta thng lu li trng thi ca ng dng trong s kin onPause v c li trng thi ng
dng trong s kin onResume
4) Tasks l g?
- Bn hiu i khi Task l kh nng thc hin mt cng vic no gia cc ng dng vi nhau,
c th l cc Activity
- V d bn ang m chng trnh qun l BlackList, trong chng trnh ny cho php m danh b
a vo danh sch en. Lc chng trnh bn s gi Activity ca ng dng danh b, sau khi ly
xong li quay tr v ng dng ca bn. Nh l 2 ng dng ny hon ton khng lin quan g ti nhau
c.

5) Life Cycle States l g?


25

Vi mi Activity thng vng i c 3 trng thi sau:


1- Running (ang kch hot)
2- Paused (tm dng)
3- Stopped (dng khng phi Destroyed)

1- Running (ang kch hot): Khi mn hnh l Foreground ( Activity nm trn cng ng dng v cho
php ngi s dng tng tc)
2- Paused (tm dng) : Activity b mt focus nhng m vn nhn thy c Activity ny (V d bn
m mt Activity mi ln di dng Dialog). Trng hp ny n vn c kh nng b h thng t ng
X trong tnh hung b nh qu t.
3- Stopped (dng khng phi Destroyed): Activity mt focus v khng nhn thy c (v d bn
m mt Activity mi ln m Full mn hnh chng hn). Trong trng hp ny n c th b h thng
X trong bt k tnh hung no.
*** Nh vy c Paused hay Stopped u c kh nng b Destroyed (hy) khi b nh cn cho vic
khc u tin hn.

26

- Trong vng i ca ng dng Android bn cn phn bit 2 loi sau:


- Visible Lifetime v Foreground Lifetime

- Visible Lifetime:
+ sy ra t sau khi gi onStart > cho ti lc gi onStop : trong trng hp ny TA vn c th thy
mn hnh Activity (c th tng tc khi n l foreground, khng tng tc c khi n khng phi
foreground nh gii thch trn)
- Foreground Lifetime:
+ Sy ra t khi gi onResume > cho ti lc gi onPause : trong sut thi gian ny Activity lun nm
trn cng v Ta c th tng tc c vi n
Nh vy bn hiu c vng i ca mt ng dng Android din ra nh th no.
27

By gi Ti s Demo ng dng Android kim tra vng i ca n:


- Bn to mt ng dng tn l : CheckLifeTimeCycle vi cu trc nh hnh di y:

- Double Click vo MainActivity.java:


- Sau bm chut phi vo mn hnh Coding/ chn Source/ chn Override / Implement
Methods :

- Mn hnh Override / Impement Methods s hin th ra nh bn di, bn chn cc


hm: onStart,onRestart, onResume, onPause, onStop, onDestroy: ri bm OK
28

Bn xem coding bn trong:

trn bn thy dng lnh trong hm onResume:


protected void onResume() {
Toast.makeText(this,onResume, Toast.LENGTH_SHORT)
.show();
super.onResume();
29

}
n gin l Ti ch hin th ln xem hm no s c triu gi ng vi Life time cycle ca Activity
- By gi bn chy ng dng vo My o Android v thc hin mt s thao tc : M mt ng dng
khc, m Menu, nhn nt Back, nhn nt Home quan st hin tng bn s hiu c cch vn
hnh cc hnh ny.
- Trong bi tp tip theo Ti s lm thm mt v d v Life time cycle bn hiu r hn v n, c
bit l tn mt chng kin u l Visible Life time, u l Foreground Life time
- Bn cn phi hiu r v Life time cycle gip ch cho vic qun l ng dng

30

Bi tp 6: Phn bit Foreground Lifetime v


Visible Lifetime
cng c thm s hiu bit v Lifetime Cycle trong bi tp 5, bi tp ny Ti s Demo cho cc bn
mt ng dng bn c th hiu r hn v Lifetime Cycle, c bit l nhn bit c Foreground
Lifetime v Visible Lifetime:
Bn to mt ng dng tn l LearnAndroidLifetime, vi cu trc nh hnh di:

- Nhn vo hnh bn trn th ng dng ny s c tng cng 3 Activities. Ch l ta s cu


hnh SubActivity1 hin th di dng Dialog (khi SubActivity1 kch hot th n s nm pha
trnMainActivity, nhng m vn nhn thy mn hnh MainActivity tc l ng thi nhn thy 2
Activity). Cn khi SubActivity2 hin th th n s chim ton b mn hnh, khng th thy
cMainActivity.
- Giao din v xml layout ca MainActivity s nh bn di:

31

y l activity_main.xml ca MainActivity
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
xmlns:tools=http://schemas.android.com/tools
android:id=@+id/LinearLayout1
android:layout_width=match_parent
android:layout_height=match_parent
android:orientation=horizontal
tools:context=.MainActivity >
<Button
android:id=@+id/button1
android:layout_width=wrap_content
android:layout_height=wrap_content
android:layout_weight=1
android:text=SubActivity1 />
<Button
android:id=@+id/button2
android:layout_weight=1
android:layout_width=wrap_content
android:layout_height=wrap_content
android:text=SubActivity2 />
</LinearLayout>
- Ti MainActivity: Khi chn nt SubActivity1, chng trnh s m SubActivity vi dng Dialog
nh hnh bn di:

32

- Khi mn hnh SubActivity1 hin th ln nh trn, nu chn Tr v MainActivity, ng dng s


ng SubActivity1.
- Bn xem cu hnh AndroidManifest.xml cho php SubActivity1 hin th di dng Dialog:
<?xml version=1.0 encoding=utf-8?>
<manifest xmlns:android=http://schemas.android.com/apk/res/android
package=tranduythanh.com
android:versionCode=1
android:versionName=1.0 >
<uses-sdk
android:minSdkVersion=14
android:targetSdkVersion=17 />
<application
android:allowBackup=true
android:icon=@drawable/ic_launcher
android:label=@string/app_name
android:theme=@style/AppTheme >
<activity
android:name=tranduythanh.com.MainActivity
android:label=@string/app_name >
<intent-filter>
<action android:name=android.intent.action.MAIN />
<category android:name=android.intent.category.LAUNCHER />
</intent-filter>
</activity>
<activity
android:name=tranduythanh.com.SubActivity1
android:label=@string/title_activity_sub_activity1
android:theme=@android:style/Theme.Dialog>
</activity>
<activity
android:name=tranduythanh.com.SubActivity2
android:label=@string/title_activity_sub_activity2 >
</activity>
</application>
</manifest>

33

- Bn xem code x l nt SubActivity1 v SubActivity2 trong class MainActivity:


package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1=(Button) findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this,
SubActivity1.class);
startActivity(intent);
}
});
Button btn2=(Button) findViewById(R.id.button2);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this,
34

SubActivity2.class);
startActivity(intent);
}
});
}
}
Phng thc findViewById tr v View theo ng Id truyn vo, mi Control trong
Android u k tha t View, y ta p kiu v cho ng kiu Button.
Dng phng thc startActivity m mt Activity, ch l Activity ny c a vo mt
Intent vi cch khai bo nh trn.
Cch chy SubActivity1 v SubActivity2 l hon ton ging nhau. Ch khc nhau lc hin
th ln mn hnh in thoi (nh gii thch trn).
Ta s hc r hn v Intent trong phn sau, tm thi phn ny cha cn phi hiu su v n.
Ch cn bit rng chy 1 Activity no th phi tin hnh nh vy.
*** Tip tc lm vic vi class MainActivity:
Bn to Override thm mt s hm : onResume, onPause, onStop, onDestroy:
@Override
protected void onResume() {
super.onResume();
Toast.makeText
(this, onResume, Toast.LENGTH_LONG)
.show();
}
@Override
protected void onPause() {
super.onPause();
35

Toast.makeText
(this, onPause, Toast.LENGTH_LONG)
.show();
}
@Override
protected void onStop() {
super.onStop();
Toast.makeText
(this, onStop, Toast.LENGTH_LONG)
.show();
}
@Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText
(this, onDestroy, Toast.LENGTH_LONG)
.show();
}
- Bn thit k SubActivity1 sao cho ging nh hnh . Bn cn lu l mi khi chng ta to mi 1
Activity th n s t ng to ra 1 Layout cho n lun:
+ 1 Bm chut phi vo Project / chn New / chn Other

36

+ 2 sau khi bm Other th mn hnh New c hin th ln, ti mn hnh ny bn chn


AndroidActivity ri bm next:

+3 tip tc bm Next cho ti mn hnh bn di, trong mn hnh ny bn t tn Activity m bn


mong mun, l bn di tn Activity s cho php bn t tn Layout cho Activity ny, thng
thng tn Layout s i km vi tn Activity do bn khng cn thit phi i tn Layout:

37

+ 4- bm Finish, v quan st ng dng s xut hin Activity v Layout cho bn. By gi bn tha h
thit k.
Trong v d ca Ti th bn ch cn ko 1 Button vo Layout ca SubActivity1
Bn t tn Button trong SubActivity1 l btntrove, cho ging vi Code tr v MainActivity di
ny:
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
public class SubActivity1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_activity1);
Button btn=(Button) findViewById(R.id.btntrove);
38

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
finish();
}
});
}
}
- Bn thy trong SubActivity1 Ti gi hm finish() khi chn Tr v MainActivity. Cng dng ca
hm finish() l tt mn hnh hin ti> nh vy n t ng m MainActivity v theo c ch
Activities Stack.
- By gi bn thc thi chng trnh v lm cc thao tc sau:
1) Chn nt SubActivity1 m Activity ny ln, quan st hin tng sy ra (ch nhng hm no
c gi)
2) Khi chn nt Tr v MainActivity, quan st hin tng sy ra (ch nhng hm no c gi)
3) Chn nt SubActivity2 m Activity ny ln, quan st hin tng sy ra (ch nhng hm no
c gi)
4) nhn nt Back ca in thoi, quan st hin tng (ch nhng hm no c gi)
*** Ti y Ti s khng gii thch th t cc hm sy ra nh th no, m dnh cho cc bn t
gii thch. Bn s thy r s khc bit trong 2 trng hp ny. V d nhin bn s t ng hiu c
Foreground Lifetime v Visible Lifetime
Cc bn c th ti coding mu
y:http://www.mediafire.com/download/7ra8h7vyttkjq6u/LearnAndroidLifetime.rar
Trong bi tp k tip Ti s hng dn cc bn cch s dng XML Layout v mt s control cn bn
thng dng cng nh cc kiu lp trnh s kin.

39

Bi tp 7: Lm quen vi cc Layout
trong Android
thit k giao din tt cho Android th trc tin cc bn phi bit s dng mt s Layout c bn
trong Android:
1) Cch to Layout v kt ni Layout vo Activity
2) Cch s dng HierarchyViewer
3) Cc Layout c bn:

FrameLayout
LinearLayout
TableLayout
RelativeLayout
AbsoluteLayout

*** ng thi bn phi bit kt hp cc Layout ny li vi nhau cho ra c giao din phc tp
nh mun.
- Ti ch nu ra mt s c im, khng th ni ht y. Cc bn s t t cp nhp sau khi quen
vi Layout.
- Trc tin bn cn bit cch to mt Layout mi v cch kt ni n vo Activity nh th no:
1) Cch to Layout v kt ni Layout vo Activity:
a) Layout mc nh u tin khi bn to mt Android Project:
- Khi bn to mt Android Project th mc nhin s c mt Activity c ch nh chy u tin khi
bn thc thi ng dng:

40

- Bn quan st hnh trn: Khi bn to mt ng dng Android th mc nhin s to lun mt Activity


thc thi u tin khi bn chy ng dng. ng vi mt Activity th n s c 1 Layout i km.
Trong hnh trn th MainActivity.java (s 1) s c layout i km l activity_main.xml (s 2 - v
bn nh lun l activity_main ny s c t ng to ra trong th mc gen ca Android, da vo
y ta kt ni Layout vo Activity).
- Nh ni nhng bi tp trc: Mi Activity mun c triu gi thnh cng trong ng dng th
bt buc n phi c khai bo trong AndroidManifest.xml (s 3). Bn double click vo Manifest v
nhn vo vng s 4, MainActivity c khai bo trong ny ng thi ng k l Activity s khi
ng lc ng dng c thc thi (xem vng Ti bi mu xanh phn intent-filter).
- Tip theo bn Double click vo tp tin MainActivity.java:

- Nhn vo hm onCreate, bn thy dng lnh : setContentView(R.layout.activity_main); chnh l


dng lnh dng kt ni Layout vo Activity. Bn nh l activity_main phi c t ng to ra
trong gen nh hnh bn di:

b) i Layout mc nh bng mt Layout khc bt k:


- to mt Layout mi, bn click chut phi vo Project/ chn New/ chn Android XML File:

41

- Khi bn chn Android XML File th mn hnh bn di xut hin: t tn cho Layout, chn kiu
Layout ri nhn nt Finish:

- trn Ti t tn l : my_new_layout, sau khi nhn nt Finish bn quan st Package Explorer:

42

- Bn thy Ti double click vo layout : my_new_layout v ko th mt s control vo giao din


nh hnh bn trn (bn nh l my_new_layout phi c t ng xut hin trong gen bn t kim
tra).
- By gi bn vo li MainActivity.java. Sa li dng lnh setContentView thnh:

- Khi ng chng trnh v bn thy ng dng s chy ci Layout mi ny ch khng phi Layout
c na:

43

2) Cch s dng HierarchyViewer:


- Nh bn bit, mt Layout phi c kt ni vo Activity no thng qua
hmsetContentView, Android s c c ch dch XML thnh Java code:

- Ta c th dng HierarchyViewer hin th cu trc UI ca mn hnh hin ti trn emulator hoc


thit b tht:
Bn vo th mc SDK ca bn / vo th mc Tools/ ri chy tp tin monitor.bat :

3) Cc Layout c bn:
44

a) FrameLayout:
- L loi Layout c bn nht, c im ca n l khi gn cc control ln giao din th cc control ny
s lun c Neo gc tri trn cng mn hnh, n khng cho php chng ta thay i v tr ca cc
control theo mt Location no .
- Cc control a vo sau n s ln trn v che khut control trc (tr khi ta thit lp
transparent cho control sau):
- Bn xem on cu trc XML di ny:
<?xml version=1.0 encoding=utf-8?>
<FrameLayout android:id=@+id/mainlayout android:layout_height=fill_parent
android:layout_width=fill_parent android:orientation=vertical
xmlns:android=http://schemas.android.com/apk/res/android&gt;
<ImageView android:layout_height=wrap_content android:layout_width=wrap_content
android:padding=5px android:src=@drawable/blue/>
<ImageView android:layout_height=wrap_content android:layout_width=wrap_content
android:padding=5px android:src=@drawable/red/>
</FrameLayout>

- Bn thy , hnh mu v mu xanh lun c neo gc tri mn hnh. Hnh mu a vo


sau s ln trn hnh mu xanh.
Ch 2 dng lnh bn di:
- android:src=@drawable/blue
- android:src=@drawable/red
L do ta ko 2 ci hnh tn l blue v red vo th mc drawable ca ng dng
b) LinearLayout
- Layout ny cho php sp xp cc control theo 2 hng trn giao din: Hng t tri qua phi v
hng t trn xung di.
45

- Bn c th dng margin, gravity, weight h tr cho vic thit k. y Ti khng c thi gian
nhiu nn ch ni c im chnh ca LinearLayout, cc bn t tm hiu thm.
- Ta c th dng Properties h tr sn trong Eclipse thit lp cc thuc tnh cho control:
- V d nh cn l cc control trn giao din ta dng layout_gravity:

- hay cn l ni dung bn trong ca control dng gravity:

- Bn cng phi bit so snh s khc bit gia Padding v Margin:

46

- V d thay i Padding (internal spacing khong cch gia ni dung bn trong so vi ng vin
ca control):

- V d v i Margin (external spacing khong cch gia control ny vi control khc):

c) TableLayout
-Cho php sp cc control theo dng li (dng v ct)
- TableLayout s xem dng no c s lng control nhiu nht xc nh rng n c bao nhiu ct
(ly dng c s lng control nhiu nht lm s ct chun).

47

- Nh vy theo hnh trn th bn phi ni l TableLayout ny c 4 ct, 3 dng.


- Dng layout_span trn cc ct:

- Dng layout_column di chuyn v tr ca control n mt ct no trn 1 dng:

- Dng stretchColumns dn u cc control, cc cell (ta thng dng du *):

d) RelativeLayout:
- RelativeLayout cho php sp xp cc control theo v tr tng i gia cc control khc trn giao
din (k c control cha n). Thng n da vo Id ca cc control khc sp xp theo v tr tng
i. Do khi lm RelativeLayout bn phi ch l t Id control cho chun xc, nu sau khi
Layout xong m bn li i Id ca cc control th giao din s b xo trn (do nu i ID th phi
i lun cc tham chiu khc sao cho khp vi Id bn mi i).
- Di y l v d v cch s dng RelativeLayout (bn nhng dng t m):

48

- Ta c th s dng cng c trong Eclipse thit k :

e) AbsoluteLayout:
- Cho php thit lp cc control giao din theo v tr ty thch:

49

- Nh vy cc Ti gii thiu s qua cch to Layout v cch s dng mt s Layout c th, ty


tng trng hp m cc bn ng dng vo. Thng thng ng vi mi mt ng dng c th th bn
phi kt hp nhiu loi Layout li vi nhau.
- Bn cn hiu r cc loi Layout gip ch cho qu trnh thit k giao din
- Bi tp sau Ti s hng dn cc bn cch s dng mt s control c bn v cch vit s kin cho
Button nh th no.

50

Bi tp 8: Cc kiu lp trnh s kin


trong Android
Bi tp ny Ti s trnh by 6 kiu lp trnh s kin trong Android. Ti s s dng mt s Control
cn bn Demo, c bit l Button dng to s kin.
1.
2.
3.
4.
5.
6.

Onclick in XML
Inline anonymous listener
Activity is listener
Listener in variable
Explicit listener class
View Subclassing

- Ti s ln lt a ra 6 v d khc nhau cho 6 kiu lp trnh s kin trn, cc bn hy c gng


theo di, n rt quan trng lm cc bi tp tip theo.
1. Onclick in XML:
- V d 1: n gin ch l cng 2 s, bn thit k giao din nh bn di:

- Khi nhn vo nt Tng 2 s, chng trnh s xut kt qu nh hnh bn trn : 80+33= 113
- Bn xem Layout Outline d thit k (ch l bn c th b LinearLayout1 i):

- Ch l ta s dng Onclick in XML:

51

- Trong on lnh trn th ta s dng android:conClick=btn_tong2so, tc l ta gn mt s


kin click cho Button ny, s kin ny tn l btn_tong2so. Ta cn khai bo mt hm btn_tong2so
trong Activity class nh hnh bn di:

- Khi chy ng dng bn s c kt qu nh bn di:

2. Inline anonymous listener


- V d vit chng trnh chuyn i nm dng lch qua nm m lch nh hnh bn di:

52

- Khi ngi s dng nhp vo EditText gi tr l 1 nm Dng Lch bt k no ri nhn nt


Chuyn i, chng trnh s chuyn nm dng lch thnh nm m lch. Trong v d trn nu
ngi s dng nhp 2013 th s ra nm m lch l Qu T.
- Ch l ta to mt anonymous listener, trc tin bn hy xem Outline XML cho d b thit k:

- chuyn t nm dng lch sang nm m lch bn cn bit mt s thng tin sau:

- By gi ta tin hnh gn s kin cho nt Chuyn i ( y id Ti l button1), m Activity


class ln vo sa lnh nh bn di:

53

- Bn t a lnh vo Bc 1, Bc 2, bc 3 trn. Cch ly d liu nhp vo t EditText


hng dn phn Onclick in XML, lm theo ci ny ly c gi tr l nm dng lch ra, sau
ly nm ny x l theo bng Can v Chi nh hng dn th Ta s ra c nm m lch tng ng.
3. Activity is listener:
- Trong cch vit s kin ny th Activity s implements interface c kiu s kin (rt nhiu loi
interface). y Ti ch v d trng hp cho Button cc trng hp khc cc bn t tm hiu v suy
lun ra.
- Ti s c mt bi v d nh sau: Hy xy dng ng dng tnh Ch s khi c th -ch vit
tt BMI (Body Mass Index )- c dng nh gi mc gy hay bo ca mt ngi. Ch s ny
c th gip xc nh mt ngi b bnh bo ph hay b bnh suy dinh dng.
+Cch tnh nh sau:
Gi W l khi lng ca mt ngi (tnh bng kg) v H l chiu cao ca ngi (tnh bng m), ch
s khi c th c tnh theo cng thc:

Phn loi nh gi nh sau:

BMI < 18: ngi gy


BMI = 18 24,9: ngi bnh thng
BMI = 25 29,9: ngi bo ph I
BMI = 30 34,9: ngi bo ph II
BMI > 35: ngi bo ph III

Ti s thit k giao din nh hnh bn di v cung cp Outline, cc bn hy thit k li nng cao


kinh nghim:

54

-Bn thy : Thng s bn trn chnh l ca chnh Ti, Tn Ti l Thanh, chiu cao 1.68 mt, cn
nng 58 kg. Khi Ti chn Tnh BMI th chng trnh s tnh ra c BMI ca Ti l 20.5 v chn
on l Bnh thng, tc l Ti c sc khe tt, dng ngi chun (c th l nim c ao ca mt
s cc bn trong lp).
- cc bn cng thng th Ti xin ni l do v sao Ti li vit phn mm ny lm v d minh
ha. Bi v bn gi ca Ti lun lun ch Ti gy (hay gi l X Quch g ). Ti chng mnh l
Ti c dng ngi chun khng cn chnh bng cch vit phn mm ny (cng thc theo chun Quc
T nn n l mt bng chng khng th chi ci). Ti ngh cc bn cng c th dng n chng
minh rng mnh khng b Bo Ph Cp 3.
- Quay tr li v d ,Bn xem Outline ca giao din ny di y (Ti c tnh khng cung cp source
XML nhm mc ch kch thch cc bn t tm ti):

- y l ni dung Coding trong Activity:


import java.text.DecimalFormat;
55

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity
implements OnClickListener{
Button btnChandoan;
EditText editTen,editChieucao,
editCannang,editBMI,editChandoan;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnChandoan=(Button) findViewById(R.id.btntinhBMI);
btnChandoan.setOnClickListener(this);
editTen=(EditText) findViewById(R.id.editten);
editChieucao=(EditText) findViewById(R.id.editchieucao);
editCannang=(EditText) findViewById(R.id.editcannang);
editBMI=(EditText) findViewById(R.id.editBMI);
editChandoan=(EditText) findViewById(R.id.editChanDoan);
}
@Override
56

public void onClick(View arg0) {


double H=Double.parseDouble(editChieucao.getText()+");
double W=Double.parseDouble(editCannang.getText()+");
double BMI=W/Math.pow(H, 2);
String chandoan=";
if(BMI<18)
{
chandoan=Bn gy;
}
else if(BMI<=24.9)
{
chandoan=Bn bnh thng;
}
else if(BMI<=29.9)
{
chandoan=Bn bo ph 1;
}
else if(BMI<=34.9)
{
chandoan=Bn bo ph 2;
}
else
{
chandoan=Bn bo ph 3;
57

}
DecimalFormat dcf=new DecimalFormat(#.0);
editBMI.setText(dcf.format(BMI));
editChandoan.setText(chandoan);
}
}
- a) Bn quan st Activity ny s implements interface OnClickListener
- b) Bn thn interface OnClickListener c m Abstract Method l onClick(View arg0) nn ta phi
Override n.
- c) Button c th hiu c s kin th Ta phi gi dng
lnh: btnChandoan.setOnClickListener(this); bn thn Activity l mt s kin nn ta dng this
truyn vo hm.
- d) Bn quan st thm Ti c s dng : DecimalFormat dcf=new DecimalFormat(#.0); Mc ch
l Ti nh dng 1 s l thp phn, bn mun 2 s l thp phn th ghi #.00 hay mun 3 th #.000
vn vn.
Bn c th load y coding mu y: http://www.mediafire.com/?71khpisxa3wmvq5
4) Listener in variable:
- Tng t nh Activity Is listener, nhng khc ch thay v implement interface cho Activity th
n li c lu tr vo mt bin c kiu Listener trong activity. Lm cch ny th ta c th chia s
chung mt bin s kin cho cc control khc nhau.
- V d bn xem hnh bn di:

58

- Bn thy , trn khai bo 1 bin c kiu listener l interface OnClickListener.


- V bin ny s c chia s cho 2 Button Login v Cancel.
- By gi Ti s cung cp v d Chuyn i F qua C v ngc li. Bn xem giao din bn di:

- Giao din bn trn s c 3 button. Ta s to mt bin s kin v chia s cho 3 Button trn.
- Bn xem Outline thit k:

- y l cng thc chuyn i:


59

-Bn xem coding Activity:


import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private Button btnFar,btnCel,btnClear;
private EditText txtFar,txtCel;
private OnClickListener myVarListener=new OnClickListener() {
@Override
public void onClick(View arg0) {
//Ly F v C t control y
if(arg0==btnFar)
{
//Bn x l chuyn i F>C theo cng thc
}
else if(arg0==btnCel)

60

{
//Bn x l chuyn i C>F theo cng thc
}
else if(arg0==btnClear)
{
txtFar.setText();
txtCel.setText();
txtFar.requestFocus();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnFar = (Button)findViewById(R.id.btnFar);
btnCel = (Button)findViewById(R.id.btnCel);
btnClear = (Button)findViewById(R.id.btnClear);
txtFar = (EditText)findViewById(R.id.txtFar);
txtCel = (EditText)findViewById(R.id.txtCel);
btnFar.setOnClickListener(myVarListener);
btnCel.setOnClickListener(myVarListener);
btnClear.setOnClickListener(myVarListener);
}
61

}
Bn t vit lnh cho 2 nt chuyn i : cch ly d liu hng dn nhng kiu lp trnh s kin
trc, bt buc bn phi ly c. Sau khi ly c th ch cn rp vo cng thc l xong.
5) Explicit listener class:
- Trng hp ny ta tch ring mt class ng vai tr l class s kin ring.
- Khi no lng coding trong ng dng khng l v phc tp th ta nn tch class s kin ring d
qun l.
Ti v d gii phng trnh bc 2, bn xem giao din bn di:

- Khi chn Tip tc, chng trnh s xa trng ton b d liu trn mn hnh ng thi focus ti
Nhp a.
- Khi chn Gii PT, chng trnh s tin hnh ly thng s a,b,c v tin hnh gii phng trnh bc
2 v cho ra kt qu nh hnh trn.
- Khi chn Thot, chng trnh s c ng li.
- Bn xem Outline di y:

62

- Tin hnh coding, bn m Activity class v coding nh bn di:


import java.text.DecimalFormat;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btnTieptuc,btnGiai,btnThoat;
EditText edita,editb,editc;
TextView txtkq;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
63

setContentView(R.layout.activity_main);
btnTieptuc=(Button) findViewById(R.id.btntieptuc);
btnGiai=(Button) findViewById(R.id.btngiaipt);
btnThoat=(Button) findViewById(R.id.btnthoat);
btnTieptuc.setOnClickListener(new MyEvent());
btnGiai.setOnClickListener(new MyEvent());
btnThoat.setOnClickListener(new MyEvent());
edita=(EditText) findViewById(R.id.edita);
editb=(EditText) findViewById(R.id.editb);
editc=(EditText) findViewById(R.id.editc);
txtkq=(TextView) findViewById(R.id.txtkq);
}
public void giaiPtb2()
{
String sa=edita.getText()+";
String sb=editb.getText()+";
String sc=editc.getText()+";
int a=Integer.parseInt(sa);
int b=Integer.parseInt(sb);
int c=Integer.parseInt(sc);
String kq=";
DecimalFormat dcf=new DecimalFormat(#.00);
if(a==0)
{
64

if(b==0)
{
if(c==0)
kq=PT v s nghim;
else
kq=PT v nghim;
}
else
{
kq=Pt c 1 No, x=+dcf.format(-c/b);
}
}
else
{
double delta=b*b-4*a*c;
if(delta<0)
{
kq=PT v nghim;
}
else if(delta==0)
{
kq=Pt c No kp x1=x2=+dcf.format(-b/(2*a));
}
else
65

{
kq=Pt c 2 No: x1=+dcf.format((-b-Math.sqrt(delta))/(2*a))+
; x2=+dcf.format((-b-Math.sqrt(delta))/(2*a));
}
}
txtkq.setText(kq);
}
private class MyEvent implements OnClickListener
{
@Override
public void onClick(View arg0) {
if(arg0==btnTieptuc)
{
edita.setText();
editb.setText();
editc.setText();
edita.requestFocus();
}
else if(arg0.getId()==R.id.btngiaipt)
{
giaiPtb2();
}
else if(arg0.getId()==R.id.btnthoat)
{
66

finish();
}
}
}
}
- Bn quan st coding bn trn. Ti to mt lp s kin tn l MyEvent, control no mun c
gn s kin ch cn gi lnh ging nh Ti gn cho Button Gii phng trnh:
btnGiai.setOnClickListener(new MyEvent());
- Trong hm public void onClick(View arg0) . Bn l lc th Ti so snh theo Object, lc th Ti
li ly Id ra so snh. y l c ca Ti, Ti mun ni rng cc bn c th kim tra xem Button
no s c chn trn giao din bng cch so snh i tng hoc ly Id ra so snh (ty lp
trnh ca mi ngi)
- y Ti c 1 li khuyn cho cc bn l khi phi x l qu nhiu dng lnh (lnh phc tp) th bn
nn vit thnh tng hm ring, v trong hm x l s kin bn ch cn gi tn hm m thi. C th l
i vi Button Gii PT th Ti li vit v gi ring hm giaiPtb2(), cn i vi Button Tip tc v
Thot th Ti li khng cn thit vit hm v x l qu n gin.
6. View Subclassing
- K thut ny khng c ph bin cho lm. Bn ch si khi thm Control ng (lc runtime) vo
mn hnh. Ta c th dng bt k k thut no (6 cch Ti va nu) thm s kin ng cho mt
Button ng.
- cch cui cng ny th bn phi override phng trnh performClick ca chnh Button control:

- Nh vy cc bn c thc hnh v cc kiu lp trnh s kin trong Android, bit c cch ly


d liu t EditText, bit x l nh dng d liu, cng c thm c Layout.
- Trong cc bi tp sp ti cc bn s c thc hnh v Toast & Alert Dialog, v rt nhiu cc
control c bn cng nh nng cao trong Android .
67

- Bn phi hiu r cc k thut lp trnh ny ty vo tng trng hp c th m bn nn quyt


nh k thut no cho ph hp.

68

Bi tp 9: Thc hnh v Toast Notification v


Alert Dialog
V trong tt c cc ng dng Ti thy rng chng ta hay s dng Toast v Alert Dialog kim tra
mt iu g , hay n gin ch l xut thng bo. V vy bi tp ny Ti s hng dn cc bn lm
quen vi Toast & Alert Dialog, sau cc bn s c thc hnh vi cc control c bn v nng cao.
- C Toast v Alert Dialog khi hin th ln th cc tin trnh (hay cc lnh) khc vn c tip tc lm
vic.
1) Toast:
- Toast c th c to v hin th trong Activity hoc trong Servive.
- Khng cho php ngi s dng tng tc
- Khi hin th sau khong thi gian no s t ng li
- C 2 gi tr mc nh (ta nn s dng 2 gi tr ny, khng nn g con s c th vo): hng
s Toast.LENGTH_SHORT hin th trong 2 giy, Toast.LENGTH_LONG hin th trong 3.5giy.
Cch to Toast:
Toast toast=Toast.makeText(YourActivity.this, Hin th g th ghi
y, Toast.LENGTH_SHORT);
toast.show();
- Khi no bn nn s dng Toast?
Theo Ti th ty bn, bn c th s dng trong trng hp hin thng bo trong cc mc thit lp
thng s cu hnh, hay n gin ch l hin th ln xem thng tin tm thi no (ging nh
kim tra mt vn sy ra chng hn).
- Hnh di y cho bn bit 1 Toast ang hin th:

2) Alert Dialog:
69

- Hin th v cho php ngi dng tng tc, v d bn nhn hnh Ti chp bn di, khi nhn nt
Cancel, chng trnh s hin th Alert Dialog hi xem c chc chn mun xa hay khng? Bm No
th khng, bm Yes th tt chng trnh.

- Cch to Alert Dialog:


AlertDialog.Builder b=new AlertDialog.Builder(YourActivity.this);
b.setTitle(Question);
b.setMessage(Are you sure you want to exit?);
b.setPositiveButton(Yes, new DialogInterface. OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}});
b.setNegativeButton(No, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
b.create().show();
70

ngha ca cc hm :
- setTitle : thit lp tiu cho Dialog
- setMessage: Thit lp ni dung cho Dialog
-setIcon : thit lp Icon
-setPositiveButton, setNegativeButton thit lp hin th Nt chn cho Dialog ( y bn khng
quan tm Nt chp nhn hay Nt hy n thuc PositiveButton hay NegativeButton v l ty thuc
bn chn. Ch l i s th 2 ca cc hm ny s l DialogInterface. OnClickListener ch
khng phi View. OnClickListener
- create() to Dialog
- show() hin th Dialog.

71

Bi tp 10: S dng TextView, EditText v


Button trong Android
- TextView, EditText, Button l 3 control c bn nht ca Android. Trong cc bi tp trc bn
c lm quen vi 3 control ny ri. Bi tp ny Ti s lm li mc ch gip cc bn n tp li ng
thi gip hiu thm c mt s thuc tnh mi ca n (trong Android ngi ta thng gi mt s
cc control l Form Widgets).
1) TextView:
- Bn ch mun hin th thng tin m khng cho php ngi dng chnh sa th nn s dng control
ny.
- TextView tng t nh JLabel bn Java, v nh Label bn C#
- Di ny Ti chp mt s thuc tnh ca TextView m chng ta thng xuyn s dng nht:

- Ta nn thit lp id cho control tin b x l.


- layout_width, layout_height nn thit lp cho control(bt buc)
- thay i mu nn dng background, thay i mu ch dng textColor
- tr gip cc bn thay i mu nn v mu ch ca cc control trong Android (dng hex color),
Ti vit chng trnh ly mu theo m hex color, cc bn c th ti v ti
: http://www.mediafire.com/?ujj2pyppdwemx69 . Giao din nh sau:

72

Chng trnh ny bn c th chn button chn custom color. ng vi mi bng mu khc


nhau th s c m Hex color khc nhau. Bn copy m ny dn vo ng dng Android ca bn th s
c mu nh mun.
Th d, mn hnh trn Hex l #3F8020, bn copy hex ny v dn vo background ca TextView
(xem hnh):

-Nh bn trn Ti ni l nn t tn Id cho control, mc ch x l mt s cng vic theo yu cu.


Da vo Id ta s ly c control theo ng Id ny, xem code bn di bit cch ly control theo
Id:
TextView txt1= (TextView) findViewById(R.id.textView1);
- Mi control u k tha t View, v hm findViewById cng tr v 1 View theo ng Id truyn
vo, l l do ta p kiu v cho ng vi TextView (cch lm nhanh: ngay dng lnh ny nhn t
hp phm Ctrl +1 l n s t p kiu nhanh cho bn)
- hin th thng tin ln control TextView ta dng lnh di y:
txt1.setText(Hello to);
- y ly thng tin bn trong control TextView ta dng lnh di y:
String msg=txt1.getText().toString();
2) EditText:
- Control ny k tha t TextView v cho php chnh sa d liu (d nhin bn c th cm chnh sa
d liu bng coding hay trong xml)
- s dng EditText rt n gin, bn ch vic ko th control ny vo giao din v tin hnh thit
lp mt s thuc tnh:

73

- Nh hnh bn trn th bn ch cn ko loi EditText m bn cn (vng s 1) ri th vo giao din


(vng s 2)
- Bn xem Ti chp mt s thuc tnh ca EditText trong hnh di ny:

- Tng t nh TextView bn cn thit lp Id, cc layout_width, layout_height


- Thuc tnh hint : hin th thng tin gi trong vng nhp d liu khi bn cha nhp bt k d
liu no vo, ch cn c d liu l phn hint s t ng mt i.
-textSize thit lp kch c font ch cho EditText
- Trong inputType bn thy Ti kt hp nhiu gi tr li vi nhau bng cch dng ton t |, tc l
EditText ny s c y cc c tnh bn v phi m ta truyn vo, v d:
+textAutoCorrect : T ng sa ng chnh t, gi s bn nhp teh th n s t ng sa thnh
the
+ vn vn bn t tm hiu thm trn mng
- Ta cng c th dng ca s Properties thit lp thuc tnh cho d dng hn (click chut vo
EditText mun i thuc tnh):
74

-Mn hnh trn cho php ta thay i thuc tnh ca control mt cch d dng.
- Tng t nh TextView, ta cng phi ly c control thng qua Id, thao tc vi d liu bn trong
EditText:
+Ly control theo Id:
EditText txtbox=(EditText) findViewById(R.id.editText1);
+Thit lp gi tr cho EditText
txtBox.setText(nhp bt c ci g vo y xem sao)
+Ly d liu bn trong EditText:
String msg=txtBox.getText().toString()
3) Button:
- Dng thit lp s kin khi ngi dng chn la.
- Cng k tha t TextView
- C 2 s kin m ngi s dng thng xuyn thao tc:

75

- By gi Ti s lm
mt v d v cch s dng 3 control ny (bn c th xem li bi tp cc kiu lp trnh s kin trong
Android):
- V d n gin l tnh cng tr nhn chia, giao din nh bn di (nhn nt no th thc hin php
ton cho nt ):

- Bn xem Layout d thit k:

- Coding mu:
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
76

import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btncong,btntru,btnnhan,btnchia;
EditText editsoa,editsob;
TextView txtkq;
OnClickListener myclick=new OnClickListener() {
@Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.btncong:
String sa=editsoa.getText()+";
String sb=editsob.getText().toString();
int a=Integer.parseInt(sa);
int b=Integer.parseInt(sb);
txtkq.setText(a+ + +b + = +(a+b));
break;
case R.id.btntru:
break;
case R.id.btnnhan:
break;
77

case R.id.btnchia:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btncong=(Button) findViewById(R.id.btncong);
btntru=(Button) findViewById(R.id.btntru);
btnnhan=(Button) findViewById(R.id.btnnhan);
btnchia=(Button) findViewById(R.id.btnchia);
editsoa=(EditText) findViewById(R.id.editsoa);
editsob=(EditText) findViewById(R.id.editsob);
txtkq=(TextView) findViewById(R.id.txtketqua);
btncong.setOnClickListener(myclick);
btntru.setOnClickListener(myclick);
btnnhan.setOnClickListener(myclick);
btnchia.setOnClickListener(myclick);
}
}
Bn hy tr li cho Ti: Hin gi on code trn Ti s dng loi S Kin no?
- Nh vy bn hiu c cch s dng TextView, EditText, Button.
78

- Cc bi tp sau Ti s ni v CheckBox, RadioButton.


- Bn phi hiu tht tt v 3 Control Ti va nu trn, n rt l c bn v quan trng, a phn ng
dng Android no cng s dng ti thiu 3 Control ny.

79

Bi tp 11: S dng Checkbox v RadioButton


trong Android
bi tp 10 bn bit cch s dng TextView, EditText v Button. Trong bi tp ny Ti s hng
dn cc bn cch s dng CheckBox v RadioButton. 2 Control ny cng rt thng xuyn c s
dng trong cc chng trnh.
- CheckBox v RadioButton u s dng chung 2 phng thc :
1) phng thc setChecked, dng thit lp checked. Nu ta gi setChecked(true) tc l cho php
control c checked, cn gi setChecked(false) th control s b unchecked.
2) phng thc isChecked, kim tra xem control c c checked hay khng. Nu c checked th tr
v true ngc li tr v false
- Checkbox cho php ta checked nhiu i tng, cn RadioButton th ti mt thi im n ch cho
ta checked 1 i tng trong cng mt group m thi.
- Nu bn mun ngi s dng c th chn nhiu la chn th bn nn s dng Checkbox, v d xem
hnh bn di:

- Ta c th thit lp cho Checkbox bt k c checked mc nh trong XML:

-Trong coding kim tra xem Checkbox c c checked hay khng th lm nh sau:

80

- Nu bn mun ngi s dng ch c chn 1 la chn trong nhiu chn la bn a ra th nn s


dng RadioButton, v d xem hnh bn di:

- Tng t nh Checkbox, ta cng c th thit lp checked cho RadioButton bt k trong XML:

- Nhn vo hnh trn bn thy l ta phi s dng


RadioGroup gom nhm cc RadioButton li cng mt nhm no , nhng RadioButton m cng
mt nhm th ti 1 thi im ch c 1 RadioButton c checked m thi. Trong mt mn hnh ta c
th to nhiu nhm RadioGroup khc nhau.
- Ti cung cp 2 cch x l RadionButton no c checked nh sau:
81

Cch 1: Da vo RadioGroup bit chnh xc Id ca RadioButton no c checked. Da vo Id


ny ta s x l ng nghip v:

- Nh hnh trn, bn thy hm getCheckedRadioButtonId() : hm ny tr v Id ca RadioButton


nm trong RadioGroup 1 c checked. Da vo Id ny bn so snh bit c trn giao din
ngi s dng ang checked la chn no.
Cch 2: Kim tra trc tip RadioButton c c checked hay khng?

C 2 cch trn u c cng chung mt mc ch ch l k thut x l khc nhau, tng t xa b


checked trong group, ta dng lnh:
group.clearChecked();
vi group l i tng RadioGroup.
- By gi Ti s demo mt v d kt hp gia RadioButton v CheckBox bn hiu su hn v 2
control ny:

82

- M t:
-

Tn ngi khng c trng v phi c t nht 3 k t

Chng minh nhn dn ch c nhp kiu s v phi c ng 9 ch s

Bng cp mc nh s chn l i hc

S thch phi chn t nht 1 chn la

Thng tin b sung c th trng

Khi bm gi thng tin, chng trnh s hin th ton b thng tin c nhn cho ngi s dng
bit (dng Alert Dialog):

- Bn xem Outline ca MainActivity d thit k:

Bn xem coding trong MainActivity:


83

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText editTen,editCMND,editBosung;
CheckBox chkdocbao,chkdocsach,chkdoccode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTen=(EditText) findViewById(R.id.editHoten);
editCMND=(EditText) findViewById(R.id.editCMND);
editBosung=(EditText) findViewById(R.id.editBosung);
chkdocbao=(CheckBox) findViewById(R.id.chkdocbao);
84

chkdoccode=(CheckBox) findViewById(R.id.chkdoccoding);
chkdocsach=(CheckBox) findViewById(R.id.chkdocsach);
Button btn=(Button) findViewById(R.id.btnguitt);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
doShowInformation();
}
});
}
public void doShowInformation()
{
//Kim tra tn hp l
String ten=editTen.getText()+";
ten=ten.trim();
if(ten.length()<3)
{
editTen.requestFocus();
editTen.selectAll();
Toast.makeText(this, Tn phi >= 3 k t, Toast.LENGTH_LONG).show();
return;
}
//kim tra CMND hp l
85

String cmnd=editCMND.getText()+";
cmnd=cmnd.trim();
if(cmnd.length()!=9)
{
editCMND.requestFocus();
editCMND.selectAll();
Toast.makeText(this, CMND phi ng 9 k t, Toast.LENGTH_LONG).show();
return;
}
//Kim tra bng cp
String bang=";
RadioGroup group=(RadioGroup) findViewById(R.id.radioGroup1);
int id=group.getCheckedRadioButtonId();
if(id==-1)
{
Toast.makeText(this, Phi chn bng cp, Toast.LENGTH_LONG).show();
return;
}
RadioButton rad=(RadioButton) findViewById(id);
bang=rad.getText()+";
//Kim tra s thch
String sothich=";
if(chkdocbao.isChecked())
sothich+=chkdocbao.getText()+\n;
86

if(chkdocsach.isChecked())
sothich+=chkdocsach.getText()+\n;
if(chkdoccode.isChecked())
sothich+=chkdoccode.getText()+\n;
String bosung=editBosung.getText()+";
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle(Thng tin c nhn);
builder.setPositiveButton(ng, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
//to ni dung
String msg=ten+\n;
msg+= cmnd+\n;
msg+=bang+\n;
msg+=sothich;
msg+=\n;
msg+=Thng tin b sung:\n;
msg+=bosung+ \n;
msg+=;
builder.setMessage(msg);//thit lp ni dung
87

builder.create().show();//hin th Dialog
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
ch cc cch dng s kin trong on code trn.
Bn c th ti coding mu y y: http://www.mediafire.com/?wqih1ln20rilsv8
Ti y bn hiu c phnn no CheckBox v RadioButton
- Bi tp k tip Ti s lm mt v d tng hp v EditText, CheckBox, Button cng ArrayList
bn hiu thm v cc control c bn ny.

88

Bi tp 12: V d tng hp TextView, EditText,


CheckBox, Button v ImageButton
trong Android
Trong bi tp 10 v bi tp 11 bn lm quen c vi cc control ny. Trong bi tp 12 Ti s lm
mt v d tng hp + kt hp vi ArrayList bn cng c thm kin thc v cc control hc.
- Vit chng trnh thanh ton tin bn sch (bn ng quan tm l chng trnh ny n c c ng
dng thc t hay khng, hy quan tm cch vit code hiu thm v cc control):

- M t yu cu:
Khi bm nt Tnh Thnh Tin (Tnh TT) chng trnh s tnh thnh tin bit rng mi cun
sch c n gi l 20000, nu l khch hng VIP th gim 10%

Khi bm nt Tip, chng trnh s lu thng tin ha n va tnh Thnh Tin vo danh sch,
ng thi xa trng d liu trong ha n v cho focus ti EditText Tn khch hng

Khi bm nt Thng k, chng trnh s hin th thng tin vo mc Thng tin thng k: tng s
KH, tng s KH VIP v tng doanh thu

Khi bm vo nt thot (dng ImageButton): hin th AlertDialog hi xem ngi s dng c


chc chn mun thot hay khng?

Dng ScrollView chng trnh c th lm vic tt hn khi s dng cc thit b c mn hnh


nh.

- Bn tham kho Outline cho d thit k:

89

- V c th bn s bc bi khi nhn thy Outline trn v vy Ti cung cp lun XML ca Outline


ny, bn ch vic copy paste vo nu lm bing:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ScrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008080"
android:gravity="center"
android:text="Chng trnh tnh tin bn sch online"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFF00"
90

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

android:text="Thng tin ha n:"


android:textSize="15sp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tn Khch Hng:" />
<EditText
android:id="@+id/edittenkh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:text="on i Nng" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="S lng sch:" />
<EditText
android:id="@+id/editsoluongsach"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
android:text="113" />
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
91

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136

<CheckBox
android:id="@+id/chklavip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:checked="true"
android:text="Khch hng l VIP" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Thnh tin:" />
<TextView
android:id="@+id/txtthanhtien"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#C0C0C0"
android:gravity="center"
android:text="2034000"
android:textColor="#008000"
android:textSize="20sp" />
</TableRow>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btntinhtt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Tnh TT" />
<Button
android:id="@+id/btntiep"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Tip" />
<Button
android:id="@+id/btnthongke"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Thng k" />
92

137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190

</LinearLayout>
</TableLayout>
<TextView
android:id="@+id/TextView01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFF00"
android:text="Thng tin thng k:"
android:textSize="15sp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1" >
<TableRow
android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tng s KH:" />
<EditText
android:id="@+id/edittongsokh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
android:text="3" />
</TableRow>
<TableRow
android:id="@+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tng s KH l VIP:" />
<EditText
android:id="@+id/edittongsokhlavip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
android:text="1" />
</TableRow>
93

191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230

<TableRow
android:id="@+id/tableRow7"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tng doanh thu:" />
<EditText
android:id="@+id/edittongdt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal"
android:text="2184000" />
</TableRow>
</TableLayout>
<TextView
android:id="@+id/textView9"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008080" />
<ImageButton
android:id="@+id/imgbtnthoat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:src="@drawable/exit" />
</LinearLayout>
</ScrollView>

Bn cn ch l cui XML c ImageButton, nhn vo thuc tnh android:src=@drawable/exit .


y bn to mt hnh c tn exit.png ri ko vo th mc drawable (bn c th t to 1 th mc
mi tn l drawable vo trong ng dng ca bn).
- Bn xem cu trc tp tin src ca ng dng ny:

94

- trn c MainActivity.java (l mn hnh chnh ca ng dng m bn thy phn gii thiu)


- class KhachHang dng lu thng tin ca khch hng: Tn khch hng, s lng mua, thnh tin,
l VIP hay khng
- class DanhSachKhachHang dng lu tr cc khch hng mua sch, ng thi cung cp mt s
hm nh: tnh tng tin, tnh tng s khch hng, tnh tng s khch hng VIP.
Di y l chi tit cho tng class:
class KhachHang:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

package tranduythanh.com;
public class KhachHang {
private String tenKh;
private int slmua;
private boolean isVip;
public static final int GIA=20000;
public KhachHang()
{
}
public KhachHang(String tenKh,int slmua,boolean isVip)
{
this.tenKh=tenKh;
this.slmua=slmua;
this.isVip=isVip;
}
public String getTenKh() {
return tenKh;
}
public void setTenKh(String tenKh) {
this.tenKh = tenKh;
}
95

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

public int getSlmua() {


return slmua;
}
public void setSlmua(int slmua) {
this.slmua = slmua;
}
public boolean isVip() {
return isVip;
}
public void setVip(boolean isVip) {
this.isVip = isVip;
}
public double tinhThanhTien()
{
return (!isVip?slmua*GIA:slmua*GIA*0.9);
}
}

Class DanhSachKhachHang:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

package tranduythanh.com;
import java.util.ArrayList;
public class DanhSachKhachHang {
ArrayList<KhachHang>listKH=new ArrayList<KhachHang>();
public void addKhachHang(KhachHang kh)
{
listKH.add(kh);
}
public double tongDoanhThu()
96

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

{
double tien=0.0;
for(KhachHang kh:listKH)
{
tien+=kh.tinhThanhTien();
}
return tien;
}
public int tongKhachHang()
{
return listKH.size();
}
public int tongKhachHangVip()
{
int s=0;
for(KhachHang kh:listKH)
{
if(kh.isVip())
s++;
}
return s;
}
}

class MainActivity:
- Dng triu gi 2 class trn v thc thi cc nghip v:
1
2

package tranduythanh.com;

97

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btnTT,btnTiep,btnTK;
ImageButton btnThoat;
EditText editTen,editSl,editTongKh,editTongKhVip,ediTongTT;
TextView txtTT;
CheckBox chkVip;
DanhSachKhachHang danhsach=new DanhSachKhachHang();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getControls();
addEvents();
}
private void getControls()
{
btnTT=(Button) findViewById(R.id.btntinhtt);
98

57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110

btnTiep=(Button) findViewById(R.id.btntiep);
btnTK=(Button) findViewById(R.id.btnthongke);
btnThoat=(ImageButton) findViewById(R.id.imgbtnthoat);
editTen=(EditText) findViewById(R.id.edittenkh);
editSl=(EditText) findViewById(R.id.editsoluongsach);
editTongKh=(EditText) findViewById(R.id.edittongsokh);
editTongKhVip=(EditText)
findViewById(R.id.edittongsokhlavip);
ediTongTT=(EditText) findViewById(R.id.edittongdt);
txtTT=(TextView) findViewById(R.id.txtthanhtien);
chkVip =(CheckBox) findViewById(R.id.chklavip);
}
private void addEvents()
{
btnTT.setOnClickListener(new ProcessMyEvent());
btnTiep.setOnClickListener(new ProcessMyEvent());
btnTK.setOnClickListener(new ProcessMyEvent());
btnThoat.setOnClickListener(new ProcessMyEvent());
}
private void doTinhTien()
{
KhachHang kh=new KhachHang();
kh.setTenKh(editTen.getText()+");
kh.setSlmua(Integer.parseInt(editSl.getText()+"));
kh.setVip(chkVip.isChecked());
txtTT.setText(kh.tinhThanhTien()+");
danhsach.addKhachHang(kh);
}
99

111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164

private void doTiep()


{
editTen.setText();
editSl.setText();
txtTT.setText();
editTen.requestFocus();
}
private void doThongKe()
{
editTongKh.setText(danhsach.tongKhachHang()+");
editTongKhVip.setText(danhsach.tongKhachHangVip()+");
ediTongTT.setText(danhsach.tongDoanhThu()+");
}
private void doThoat()
{
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle(hi thot chng trnh);
builder.setMessage(Mun thot chng trnh ny h?);
builder.setNegativeButton(Khng, new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setPositiveButton(C, new
DialogInterface.OnClickListener() {
@Override
100

165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

public void onClick(DialogInterface dialog, int which) {


finish();
}
});
builder.create().show();
}
private class ProcessMyEvent implements OnClickListener
{
@Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.btntinhtt:
doTinhTien();
break;
case R.id.btntiep:
doTiep();
break;
case R.id.btnthongke:
doThongKe();
break;
case R.id.imgbtnthoat:
doThoat();
break;
}
}
}
}
101

219
- Trong MainActivity Ti c tnh tch cc nghip v ra thnh cc hm ring bit nh vy
bn d dng x l. Chng ta nn tp vit nh vy Coding c sch s, khi c li sy ra
cng gip cc bn d Fixed bug, sai hm no th sa hm m n khng b nh hng ti
cc nghip v khc.
- Bn c th load y coding mu trong link ny: http://www.mediafire.com/?lgq5g2l28xb222c
- Bn phi hiu cch lm bi tp ny ng dng cho cc phn sau.
- Hy thc hnh bi ny nhiu ln cho ti khi thc s hiu logic ca n.
- Bi tp tip theo bn s c hc v cc control nng cao trong Android, v ta s thc hnh tht k
tng control c th, u tin l ListView (control rt thng xuyn c s dng trong mt chng
trnh Android no )

102

Bi tp 13: Thc hnh v ListView


trong Android
Trong cc bi tp trc cc bn c lm quen vi nhiu control c bn, bi tp ny bn s c
lm quen vi control nng cao, c th l ListView. Trong ng dng cn lu tr v hin th danh sch
cc thng tin a phn chng ta si control ListView. Hin ti bn ch cn bit s dng ListView c
sn ca Android l c ri, trong cc bi tp tip theo Ti s hng dn cc bn Custom Layout li
ListView (t lm mi ListView theo mnh).
- Bi tp ny Ti s cung cp nhiu cch hnh x vi ListView, ng vi mi cch l c cc v d mu
khc nhau, v vy cc bn nn c gng theo di v thc hnh li nhng v d.
- Bn hy thc hnh tt 5 trng hp Ti trnh by di y:
1) Trng hp 1:- S dng ListView control vi mng d liu nh sn.
-Trng hp ny Ti a ra mt v d n gin l cho php hin th mng d liu ln trn ListView,
bn xem hnh minh ha:

- Giao din trn c 2 control:


+ListView : dng hin th mng d liu
+TextView c mu xanh lc: Dng hin th v tr v gi tr ca phn t c chn trong ListView
- Bn to mt Android Project tn l : Vidu_ListView_HardCode_Array, chn layout ph hp
v ko th cc control vo giao din:

103

- Di y l ni dung ca activity_main.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/txtselection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#dd0230dd"
android:hint="Selected person here" />
<ListView
android:id="@+id/lvperson"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

-t id cho Listview l lvperson (nhn dng lnh 15 trn), bn c th nh dng thm mt s c


tnh khc nhng trong bi tp ny th cha cn thit, ch cn hin th c d liu ln giao din l
t yu cu.
- By gi bn m MainActivity.java ln vit code:
1
2
3
4
5
6
7
8
9
10
11
12

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
104

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1. Khi to d liu cho mng arr (cn gi l data source)
final String arr[]={"Teo","Ty","Bin","Bo"};
//2. Ly i tng Listview da vo id
ListView lv=(ListView) findViewById(R.id.lvperson);
//3. Gn Data source vo ArrayAdapter
ArrayAdapter<String>adapter=new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, arr);
//4. a Data source vo ListView
lv.setAdapter(adapter);
final TextView txt=(TextView) findViewById(R.id.txtselection);
//5. Thit lp s kin cho Listview, khi chn phn t no th
hin th ln TextView
lv.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,
View arg1,
int arg2,
long arg3) {
//i s arg2 l v tr phn t trong Data Source (arr)
txt.setText("position :"+arg2+" ; value ="+arr[arg2]);
}
});
}
}

- Ti gii thch tng dng lnh bn trong code, gi Ti gii thch thm v ArrayAdapter, bn
nhn vo dng lnh 21.
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,android.R.
layout.simple_list_item_1, arr);
- D liu t Data source (arr) s c gn vo ArrayAdapter, ArrayAdapter s gn vo ListView.
- Bn nhn vo i s u tin ca constructor ArrayAdapter : this, chnh l context ca Activity hin
ti, bn c th vit MainActivity.this (nu bn vit nh th ny th bt k v tr no n cng hiu l
context ca MainActivity, do cc bn nn vit nh th ny bn c th copy paste n ti bt k
v tr no th n cng hiu)
- i s th 2 android.R.layout.simple_list_item_1 : bn android Ti t mu xanh, y chnh
l layout Listview m c Android xy dng sn, cc bi tp k tip ta s t xy dng m khng s
dng ci c sn ny. Nh vy th simple_list_item_1 lu u? v bn trong n nh th no?. N
c lu trong SDK/platforms/android-api (x)/data/res/layout/simple_list_item_1.xml. Bn c th
xem ni dung v v tr ca layout ny mt cch nhanh chng bng phm Ctrl + click chut vo
dng lnh ny, bn s thy nh bn di:

105

- i s th 3: chnh l arr (data source), bn c th truyn vo ArrayList.


- Nhn vo dng lnh 27 ch gn s kin cho ListView (bn nh l ch cn g mt vi k t u ri
nhn Ctrl+ Space Bar th cc lnh ng sau s t ng xut hin ra cho bn):
+ Ta c interface AdapterView.OnItemClickListener, n dng thit lp s kin cho ListView,
interface ny c 1 phng thc tru tng l onItemClick nn ta override n v x l trong ny. Bn
cng nh l ch ny khng c g bng tay m ch cn nhn t hp phm Ctrl + 1 chn add
unimplement method l n t xut hin. Ngoi ra n cn nhiu s kin khc cc bn t tm hiu
thm.
Bn c th ti code y y:http://www.mediafire.com/?uwy4lp0e1jt0mik
2) Trng hp 2: S dng ListView vi mng d liu c lu trong Xml:
- Giao din v x l s kin trong trng hp ny l y x trng hp 1. Ch khc ch l d liu s
c load t XML, nn Ti ch hng dn cch to String Array trong XML v cch load
String-Array trong coding nh th no.
- Bn to mt Android Project tn l: Vidu_ListView_Xml_Array
- to String Array trong XML bn lm nh sau:
Bc 1: Bm chut phi vo th mc values ca Project/ chn New/Android XML File:

106

- Bc 2: Mn hnh New Android XML hin th ln, bn chn thng s ging nh hnh bn di, t
tn tp tin l mystrings.xml ri nhn nt Finish:

Xem kt qu khi bm nt Finish v quan st cho nhn xt:

107

Ch l ta cng c th thm d liu vo tp tin strings.xml, nhng y l ca Ti, Ti mun


hng dn cc bn cch to 1 tp tin XML mi v thm d liu vo tp tin mi ny lun.
Bc 3: chn tab Resource hnh trn:

- Bc 4: Bm nt Add mn hnh trn thm String-Array:

108

mn hnh trn bn chn String Array ri nhn OK:


- Bc 5: t tn cho String Array, sau khi nhn OK th mn hnh bn di hin th ra, bn t tn
String Array ny l myarray ri nhn ctrl+s lu:

- Bc 6: Thm cc phn t vo String Array, tip tc bm nt Add mn hnh bn trn:

109

-Sau khi nhn OK th n s cho php bn nhp gi tr cho phn t.


- Bn c lp lin tc thao tc bc 6 ny, thm bao nhiu phn t th click tng ln Add, y
l Ti thm 3 phn t, bn xem hnh:

- Xem ni dung XML:


1
2
3
4
5
6
7
8

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


<resources>
<string-array name="myarray">
<item >Trn Vn To</item>
<item >Nguyn Th Tt</item>
<item >H Vn Hin</item>
</string-array>
</resources>

- Nh vy bn bit cch tao 1 tp tin XML v bit cch to String Array cng nh to cc phn t
nm bn trong n, By gi trong Coding ta s da vo myarray c ton b d liu t XML ra.
Bn cng ch l myarray khi bn to ra trn th n cng c to ra trong gen:
110

- Nh bn thy , trong coding ta s da vo y ly ra: R.array.myarray.


* M MainActivity.java ln:
- Nh Ti ni l mi th n y x nh trng hp s 1, d trong trng hp ny Ti ch vit
dng lnh c d liu t XML v mt Mng (thay v trng hp 1 Ti hardcode my phn t khi
khai bo mng), cn cc phn khc bn t lm ging trng hp 1:
final String arr[]=getResources().getStringArray(R.array.myarray);
Tc l bn thay th dng lnh th 17 trong trng hp 1 ca MainActivity.java bng dng lnh trn.
Thc thi ng dng bn s c kt qu nh hnh bn di:

- Ti ngh ti y bn tht s hiu trng hp 2.


- Bn c th ti ton b coding mu y: http://www.mediafire.com/?168jsno9iq85qsc
3) Trng hp 3: S dng ArrayList v Listview control:
- Trng hp ny Ti mun hng dn cc bn cch s dng ArrayList lu tr d liu v ln
ListView nh th no, bn xem giao din ca chng trnh:

111

- M t:
+ Nhp d liu v nhn nt Nhp th s a vo ArrayList v hin th ln ListView
+ Nhn vo phn t no th hin th v tr v gi tr ca phn t ln TextView
+ Nhn tht lu (long click ) vo phn t no trn ListView th s xa phn t .
* To Android Project tn: Vidu_ListView_ArrayList,
Xem Layout XML ca ng dng (activity_main.xml):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="@+id/txtTen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:inputType="text"
android:layout_toRightOf="@+id/textView1"
android:ems="10" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/txtTen"
android:layout_alignBottom="@+id/txtTen"
android:layout_alignParentLeft="true"
android:background="#deb887"
android:text="Nhp tn:" />
<Button
android:id="@+id/btnNhap"
android:layout_width="wrap_content"
112

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

android:layout_height="wrap_content"
android:layout_alignRight="@+id/txtTen"
android:layout_below="@+id/txtTen"
android:layout_toRightOf="@+id/textView1"
android:textAlignment="center"
android:text="Nhp" />
<TextView
android:id="@+id/txtselection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/btnNhap"
android:background="#007380" />
<ListView
android:id="@+id/lvperson"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/txtselection"
android:background="#cccccc" >
</ListView>
</RelativeLayout>

Xem MainActivity.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

package tranduythanh.com;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText txtten;
TextView txtchon;
Button btn;
ListView lv;
ArrayList<String>arrList=null;
ArrayAdapter<String> adapter=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtten=(EditText) findViewById(R.id.txtTen);
txtchon=(TextView) findViewById(R.id.txtselection);
113

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

lv=(ListView) findViewById(R.id.lvperson);
//1. To ArrayList object
arrList=new ArrayList<String>();
//2. Gn Data Source (ArrayList object) vo ArrayAdapter
adapter=new ArrayAdapter<String>
(this,
android.R.layout.simple_list_item_1,
arrList);
//3. gn Adapter vo ListView
lv.setAdapter(adapter);
btn=(Button) findViewById(R.id.btnNhap);
//4. X l s kin nhn nt Nhp
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
arrList.add(txtten.getText()+"");
adapter.notifyDataSetChanged();
}
});
//5. X l s kin chn mt phn t trong ListView
lv.setOnItemClickListener(new AdapterView
.OnItemClickListener() {
public void onItemClick(
AdapterView<?> arg0,View arg1,
int arg2,long arg3) {
txtchon.setText("position : "+ arg2+
"; value ="+arrList.get(arg2));
}
});
//6. x l s kin Long click
lv.setOnItemLongClickListener(new AdapterView
.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View
arg1,
int arg2, long arg3) {
arrList.remove(arg2);//xa phn t th arg2
adapter.notifyDataSetChanged();
return false;
}
});
}
}

Ti gii thch thm v coding:


ArrayList bn c hc trong mn Java 1 ri. y Ti ni
hm adapter.notifyDataSetChanged(); Bn ch l ArrayList c gn vo adapter nn mi s
thay i trong ArrayList th adapter u nhn bit c. Khi c s thay i trong ArrayList bn ch
cn gi notifyDataSetChanged th ListView s c cp nht (bi v Adapter c gn vo
ListView).

114

- S kin setOnItemLongClickListener, c gn cho ListView Item, khi nhn lu t 2.5 ti 3 giy


th s kin ny s sy ra. Tng t nh setOnItemClickListener , i s c tn arg2 c dng
xc nh c v tr ca phn t nm trong ArrayList.
- Bn c th vo y ti coding mu: http://www.mediafire.com/?64k77e8yiazar8i
4) Trng hp 4: S dng ArrayList v ListView nhng tng phn t trong ArrayList l cc
Object bt k:
- Ti c mt v d v hin th danh sch nhn vin theo m hnh sau:

- C 2 loi nhn vin : Nhn vin chnh thc (EmployeeFullTime ) v nhn vin thi v
(EmployeePartime).
- Mi nhn vin s c cch tnh lng khc nhau (tn phng thc tnh lng ging nhau)
- Mi nhn vin c phng thc toString xut thng tin, Ni dung xut khc nhau. Thm
FullTime ng sau Id v Name i vi nhn vin chnh thc. Thm Partime ng sau Id v Name i
vi nhn vin thi v.
- Xem giao din chng trnh:

115

-To mt Android Project tn: Vidu_ListView_ArrayList_Object, cu trc nh bn di:

- Layout XML (activity_main.xml):


1
2
3
4
5
6
7
8
9
10

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
116

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:gravity="center"
android:text="Qun l nhn vin"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TableLayout
android:layout_width="match_parent"
android:stretchColumns="*"
android:layout_height="wrap_content" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M NV:" />
<EditText
android:id="@+id/editMa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tn NV:" />
<EditText
android:id="@+id/editTen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2"
android:ems="10" />
117

65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118

</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loi NV:" />
<RadioGroup
android:id="@+id/radiogroud1"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/radChinhthuc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Chnh thc" />
<RadioButton
android:id="@+id/radThoivu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Thi v" />
</RadioGroup>
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnnhap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="Nhp NV" />
</TableRow>
</TableLayout>
<TextView
android:id="@+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000" />
<ListView
118

119
120
121
122
123
124
125

android:id="@+id/lvnhanvien"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

- Xem ni dung tng class:


- Abstract class Employee:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

package tranduythanh.com;
public abstract class Employee {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract double TinhLuong();
@Override
public String toString() {
// TODO Auto-generated method stub
return this.id+" - "+this.name;
}
}

- class EmployeeFullTime:
1
2
3
4
5
6
7
8
9

package tranduythanh.com;
public class EmployeeFullTime extends Employee {
@Override
public double TinhLuong() {
return 500;
}
@Override
119

10
11
12
13
14

public String toString() {


// TODO Auto-generated method stub
return super.toString() +" -->FullTime="+TinhLuong();
}
}

- Class EmployeePartTime:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

package tranduythanh.com;
public class EmployeePartTime extends Employee {
@Override
public double TinhLuong() {
// TODO Auto-generated method stub
return 150;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString() +" -->PartTime="+TinhLuong();
}
}

- Bn thy l 2 class dn xut t Employee Ti lm n gin l cch tnh lng khc nhau. i vi
FullTime th lng 500, Partime lng 150. v hm Xut toString() cng khc nhau 1 x.
- y ta s p dng tnh a hnh thng qua tha k, ch cn dng mt bin c kiu Employee,
nhng n c th hiu FullTime hoc Partime v xut ra thng tin ng nh mnh mong i.
- Xem class MainActivity.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

package tranduythanh.com;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
public class MainActivity extends Activity {
EditText editId,editName;
Button btnNhap;
RadioGroup radgroup;
ListView lvNhanvien;
ArrayList<Employee>arrEmployee=new ArrayList<Employee>();
ArrayAdapter<Employee>adapter=null;
120

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

//Khai bo 1 employee object


Employee employee=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editId=(EditText) findViewById(R.id.editMa);
editName=(EditText) findViewById(R.id.editTen);
btnNhap=(Button) findViewById(R.id.btnnhap);
radgroup=(RadioGroup) findViewById(R.id.radiogroud1);
lvNhanvien=(ListView) findViewById(R.id.lvnhanvien);
//a Data Source l cc employee vo Adapter
adapter=new ArrayAdapter<Employee>(this,
android.R.layout.simple_list_item_1,
arrEmployee);
//a adapter vo ListView
lvNhanvien.setAdapter(adapter);
btnNhap.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
processNhap();
}
});
}
//X l s kin nhp
public void processNhap()
{
//Ly ra ng id ca Radio Button c checked
int radId=radgroup.getCheckedRadioButtonId();
String id=editId.getText()+"";
String name=editName.getText()+"";
if(radId==R.id.radChinhthuc)
{
//to instance l FullTime
employee=new EmployeeFullTime();
}
else
{
//To instance l Partime
employee=new EmployeePartTime();
}
//FullTime hay Partime th cng l Employee
//nn c cc hm ny l hin nhin
employee.setId(id);
employee.setName(name);
//a employee vo ArrayList
arrEmployee.add(employee);
//Cp nhp giao din
adapter.notifyDataSetChanged();
}
}
121

76
- Chng trnh s t ng hin th ng loi Employee m ta chn la trn giao din, y bn li
c n tp thm v tnh a hnh trong java. ng vi mi loi Employee n s t ng gi hm
toString ca loi .
V d: Nu Employee l FullTime th n gi toString ca FullTime v ngc li vi PartTime
cng vy n s ly toString ca PartTime.
- n y bn hiu tng i su v ListView, bn c th ti coding mu
y: http://www.mediafire.com/?o1we6e0mw8cpbba
5)Trng hp 5: S dng ListView nhng di dng ListActivity:
- Thay v k tha t Activity, ta s cho k tha t ListActivity.
- V d nhin cch t Id cho ListView cng c s khc bit.
- Bn xem giao din bn di:

- Xem cch lm XML layout (activity_main.xml):


1
2
3
4
5
6
7
8
9
10
11
12

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/selection"
android:layout_width="match_parent"
122

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

android:layout_height="wrap_content"
android:background="#008000"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="@android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Khng c g c" />
</LinearLayout>

- Bn nhn vo dng lnh th 18:


android:id=@android:id/list, bn vit y x nh th ny. Bi v n l id c nh ngha sn bn
trong Android.
- Tip tc nhn vo dng lnh 24:
android:id=@android:id/empty , cng l c sn ca Android. N c tc dng t ng thng bo
khi ListView ca bn khng c bt k mt phn t no c.
- Xem class MainActivity.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

package tranduythanh.com;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends ListActivity {
TextView selection;
String arr[]={"Intel","SamSung",
"Nokia","Simen","AMD",
"KIC","ECD"};
ArrayAdapter<String >adapter=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Thit lp Data Source cho Adapter
adapter=new ArrayAdapter<String>
123

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

(this,
android.R.layout.simple_list_item_1,
arr);
//Gn Adapter vo ListView
//Nh l phi t id cho ListView theo ng quy tc
setListAdapter(adapter);
selection=(TextView) findViewById(R.id.selection);
}
@Override
protected void onListItemClick(ListView l, View v, int
position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String txt="postion = "+position +"; value ="+arr[position];
selection.setText(txt);
}
}

- Bn nhn vo dng lnh s 10: bn thy y, Ti cho k tha t ListActivity ch khng


phiActivity. (Android vit class ListActivity k tha t Activity ri). Tc l ListActivity cng
chnh l Activity.
- Bn nhn vo dng lnh s 28:
setListAdapter(adapter);
y ta hon ton khng Li control ListView ra. M ta ch cn gi hm setListAdapter
th ListView cng t ng cp nhp d liu. Bn phi lm chnh xc 2 ni th mi c nh vy:
1. Kt tha t ListActivity,
2. t id cho ListView theo ng quy tc android:id=@android:id/list
- Bn load coding y y: http://www.mediafire.com/?mjxgs1yv0mvujuz
*** Nh vy bn thc hnh xong 5 trng hp m Ti nu. Ti hi vng cc bn hy lm li
nhiu ln c th hiu su hn v n.
Bi tp k tip bn s c thc hnh v cch Custom layout li ListView theo thch ca bn.

124

Bi tp 14: Thc hnh v Custom Layout cho


ListView trong Android
bi tp 13 bn c thc hnh vi ListView control. Trong bi tp ny bn s hc cch Custom
li layout cho ListView trong ng dng Android ca bn. Ti ngh bi tp ny n rt quan trng v
thc t bi v trong cc ng dng Android c lin quan ti ListView th a phn chng ta phi
custom li cho ng vi yu cu ca khch hng.
Ti c lm mt v d v qun l nhn vin vi giao din bn di y:

- Bn quan st l phn danh sch nhn vin bn di l Custom Layout.


- Mi dng trong ListView s c 3 i tng: ImageView, TextView v Checkbox.
- Khi nhp nhn vin nu ngi s dng chn N th s hin th hnh l con gi, nu chn Nam th
hin th hnh l con trai (bn nhn danh sch hnh nh nh 1616 ListView).
- M v tn ca nhn vin s c hin th vo TextView
- Checkbox cho php ngi s dng checked (nhm nh du nhng nhn vin mun xa, y cho
php xa nhiu nhn vin)
- Bn Ti c thm 1 ImageButton c hnh mu Cho , n dng xa tt c cc nhn vin
c Checked trong ListView, sau khi xa thnh cng th phi cp nht li ListView.
- lm c iu trn th ta s k tha t ArrayAdapter v override phng thc getView, c
th:
- Bn xem Cu trc chng trnh qun l nhn vin:
125

- Ti to thm th mc drawable v ko th 3 icon m Ti s dng vo (bn cng to th mc tn y


x vy). Nh l tn hnh phi vit lin v ch thng u tin.
- Trong th mc layout: Ti to thm my_item_layout.xml dng Custom li ListView, di y
l cu trc XML ca n:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/imgitem"
android:layout_width="22dip"
android:layout_height="22dip"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:paddingTop="2dp"
android:layout_marginTop="4dp"
android:contentDescription="here"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/txtitem"
android:layout_height="wrap_content"
android:layout_width="0dip"
android:layout_weight="2"
android:layout_marginTop="4dp"
android:paddingLeft="2dp"
126

26
27
28
29
30
31
32
33
34
35

android:paddingRight="2dp"
android:paddingTop="2dp"
android:textSize="15sp" />
<CheckBox
android:id="@+id/chkitem"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

- Ta s da vo cc id trong ny x l trong hm getView ca class m ta k tha t ArrayAdapter


(cc id trn l imgitem i din cho hnh l N hay Nam, txtitem dng hin th m v tn nhn
vin, chkitem dng x l Checked)
- Bn xem activity_main.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:gravity="center"
android:text="Qun l nhn vin"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M NV:" />
<EditText
127

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

android:id="@+id/editMa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tn NV:" />
<EditText
android:id="@+id/editTen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gii tnh:" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/radNu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="N" />
<RadioButton
android:id="@+id/radNam"
128

91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nam" />
</RadioGroup>
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnNhap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="Nhp NV" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="9"
android:background="#008000"
android:layout_marginTop="2dp"
android:text="Danh sch nhn vin:"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<ImageButton
android:id="@+id/btndelete"
android:layout_width="30dip"
android:layout_height="30dip"
android:src="@drawable/deleteicon" />
</LinearLayout>
<ListView
android:id="@+id/lvnhanvien"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

129

- Layout main ny chnh l giao din chnh ca ng dng.


- Di y l cc class h tr x l nghip v:

- Class Employee dng lu tr thng tin nhn vin: M nhn


vin, tn nhn vin, gii tnh
- Class MyArrayAdapter k tha t ArrayAdapter, mc ch ca n l gip chng ta Custom li
layout cho ListView.
- Cui cng MainActivity.
- By gi ta vo chi tit tng class:
1) class Employee:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

package tranduythanh.com;
public class Employee {
private String id;
private String name;
private boolean gender;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
@Override
public String toString() {
return this.id+"-"+this.name;
}
}

130

2) class MyArrayAdapter:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

package tranduythanh.com;
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyArrayAdapter extends
ArrayAdapter<Employee>
{
Activity context=null;
ArrayList<Employee>myArray=null;
int layoutId;
/**
* Constructor ny dng khi to cc gi tr
* t MainActivity truyn vo
* @param context : l Activity t Main
* @param layoutId: L layout custom do ta to
(my_item_layout.xml)
* @param arr : Danh sch nhn vin truyn t Main
*/
public MyArrayAdapter(Activity context,
int layoutId,
ArrayList<Employee>arr){
super(context, layoutId, arr);
this.context=context;
this.layoutId=layoutId;
this.myArray=arr;
}
/**
* hm dng custom layout, ta phi override li hm ny
* t MainActivity truyn vo
* @param position : l v tr ca phn t trong danh sch
nhn vin
* @param convertView: convertView, dng n x l Item
* @param parent : Danh sch nhn vin truyn t Main
* @return View: tr v chnh convertView
*/
public View getView(int position, View convertView,
ViewGroup parent) {
/**
* bn ch l y Ti khng lm:
* if(convertView==null)
* {
* LayoutInflater inflater=
* context.getLayoutInflater();
* convertView=inflater.inflate(layoutId, null);
* }
* L do l ta phi x l xa phn t Checked, nu dng If
131

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

th
* n li checked cho cc phn t khc sau khi xa v
convertView
* lu li trng thi trc
*/
LayoutInflater inflater=
context.getLayoutInflater();
convertView=inflater.inflate(layoutId, null);
//ch l test thi, bn c th b If i
if(myArray.size()>0 && position>=0)
{
//dng lnh ly TextView ra hin th M v tn ln
final TextView txtdisplay=(TextView)
convertView.findViewById(R.id.txtitem);
//ly ra nhn vin th position
final Employee emp=myArray.get(position);
//a thng tin ln TextView
//emp.toString() s tr v Id v Name
txtdisplay.setText(emp.toString());
//ly ImageView ra thit lp hnh nh cho ng
final ImageView imgitem=(ImageView)
convertView.findViewById(R.id.imgitem);
//nu l N th ly hnh con gi
if(emp.isGender())
imgitem.setImageResource(R.drawable.girlicon);
else//nu l Nam th ly hnh con trai
imgitem.setImageResource(R.drawable.boyicon );
}
//V View l Object l dng tham chiu i tng, nn
//mi s thay i ca cc object bn trong convertView
//th n cng bit s thay i
return convertView;//tr v View ny, tc l tr lun
//v cc thng s mi m ta va thay i
}
}

- y l class quan trng nht, mi nht; dng custom layout.


3) class MainActivity:
1
2
3
4
5
6
7
8
9
10
11
12
13
14

package tranduythanh.com;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioGroup;
132

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

public class MainActivity extends Activity {


ArrayList<Employee>arrEmployee=new ArrayList<Employee>();
//S dng MyArrayAdapter thay th ArrayAdapter
MyArrayAdapter adapter=null;
ListView lvNhanvien=null;
Button btnNhap;
ImageButton btnRemoveAll;
EditText editMa,editTen;
RadioGroup genderGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnNhap=(Button) findViewById(R.id.btnNhap);
btnRemoveAll=(ImageButton) findViewById(R.id.btndelete);
editMa=(EditText) findViewById(R.id.editMa);
editTen=(EditText) findViewById(R.id.editTen);
genderGroup=(RadioGroup) findViewById(R.id.radioGroup1);
lvNhanvien=(ListView) findViewById(R.id.lvnhanvien);
arrEmployee=new ArrayList<Employee>();
//Khi to i tng adapter v gn Data source
adapter=new MyArrayAdapter(
this,
R.layout.my_item_layout,// ly custom layout
arrEmployee/*thit lp data source*/);
lvNhanvien.setAdapter(adapter);//gn Adapter vo Lisview
btnNhap.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
xulyNhap();
}
});
btnRemoveAll.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
xulyXoa();
}
});
}
//gi hm x l nhp thng tin nhn vin
public void xulyNhap()
{
String ma=editMa.getText()+"";
String ten=editTen.getText()+"";
boolean gioitinh=false;//Nam =false
133

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

if(genderGroup.getCheckedRadioButtonId()==R.id.radNu)
gioitinh=true;
//To mt employee
Employee emp=new Employee();
emp.setId(ma);
emp.setName(ten);
emp.setGender(gioitinh);
//a vo danh sch
arrEmployee.add(emp);
//gi hm cp nht giao din
adapter.notifyDataSetChanged();
//Sau khi update th xa trng d liu v cho editma
focus
editMa.setText("");
editTen.setText("");
editMa.requestFocus();
}
//hm x l xa
public void xulyXoa()
{
//ta nn i ngc danh sch, kim tra phn t no checked
//th xa ng v tr ra khi arrEmployee
for(int i=lvNhanvien.getChildCount()-1;i>=0;i--)
{
//ly ra dng th i trong ListView
//Dng th i s c 3 phn t: ImageView, TextView,
Checkbox
View v=lvNhanvien.getChildAt(i);
//Ta ch ly CheckBox ra kim tra
CheckBox chk=(CheckBox) v.findViewById(R.id.chkitem);
//Nu n Checked th xa ra khi arrEmployee
if(chk.isChecked())
{
//xa phn t th i ra khi danh sch
arrEmployee.remove(i);
}
}
//Sau khi xa xong th gi update giao din
adapter.notifyDataSetChanged();
}
}

- By gi bn thc hin chng trnh v nhp mt s nhn vin, ri checked ri nhn xa:

134

- Bn hy tm hiu thm trn mng v cch x l cc phn t khi custom, y Ti cha x l xong:
V d bn cha th chn c vo tng phn t trong ListView (cho d bn c nghin rng ngoy
mnh ngn tay vo th n cng khng lung lay, Nu bn b CheckBox i th li c) Nn bn tm
hiu thm phn x l ny (how to selected item in custom ListView).
- Bn c th ti ton b coding mu y:http://www.mediafire.com/?16tw6xf55nivr8k
- Bn nn lm tt bi ny v n rt quan trng v hay.
- Trong cc bi tp tip theo bn s c thc hnh v Spinner, GridView, kt hp Spinner vi
ListView, kt hp Spinner vi GridView.

135

Bi tp 15: Thc hnh v Spinner


trong Android
- Trong bi tp ny cc bn s thc hnh cch s dng Spinner.
- Spinner tng t nh ComboBox trong C#, tng t nh JComboBox trong Java.
- Nu bn hiu v ListView th vic hiu Spinner l chuyn thng.
- Cch d liu ln Spinner l y x nh ln ListView, n ch khc mt ch duy nht trong
ArrayAdapter l ta phi gi setDropDownViewResource.
- Bn xem hnh v d di y v Spinner:

- V d trn lm rt n gin, bn ch vic ko 2 control: TextView v Spinner vo ng dng


(xemactivity_spinner.xml):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".SpinnerActivity" >
<TextView
android:id="@+id/selection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#007380"
android:hint="selected here"
android:textColor="#ff003c" />
<Spinner
136

17
18
19

android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

- y Ti t Id cho spinner l spinner1 (nhn dng lnh 16).


- Coding SpinnerActivity.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class SpinnerActivity extends Activity {
//To mt mng d liu gi
String arr[]={
"Hng in t",
"Hng ha cht",
"Hng gia dng"};
TextView selection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
selection =(TextView) findViewById(R.id.selection);
//Ly i tng Spinner ra
Spinner spin=(Spinner) findViewById(R.id.spinner1);
//Gn Data source (arr) vo Adapter
ArrayAdapter<String> adapter=new ArrayAdapter<String>
(
this,
android.R.layout.simple_spinner_item,
arr
);
//phi gi lnh ny hin th danh sch cho Spinner
adapter.setDropDownViewResource
(android.R.layout.simple_list_item_single_choice);
//Thit lp adapter cho Spinner
spin.setAdapter(adapter);
//thit lp s kin chn phn t cho Spinner
spin.setOnItemSelectedListener(new MyProcessEvent());
}
//Class to s kin
private class MyProcessEvent implements
OnItemSelectedListener
{
//Khi c chn la th vo hm ny
137

46
47
48
49
50
51
52
53
54
55
56
57
58

public void onItemSelected(AdapterView<?> arg0,


View arg1,
int arg2,
long arg3) {
//arg2 l phn t c chn trong data source
selection.setText(arr[arg2]);
}
//Nu khng chn g c
public void onNothingSelected(AdapterView<?> arg0) {
selection.setText("");
}
}
}

- Bn xem Ti gii thch di ny:

- Bn thy android.R.layout.simple_spinner_item dng hin th phn t bn chn ln


spinner. Tng t nh trong ListView bn c th custom li
- Dng lnh di: android.R.layout.simple_list_item_single_choice hin th danh sch cc phn
t trong Spinner khi bn nhn vo xem Spinner. Bn phi gi hm setDropDownViewResource nu
khng n s li chng trnh khi bn nhn vo xem. Bn c th dng layout khc nhau, chng hn
bn c th thay th bng : android.R.layout.simple_spinner_dropdown_item
- Nh vy bn lm quen c vi Spinner, bn c th load code mu
y: http://www.mediafire.com/?1pmikmscb30po3s
- Ban u Ti tnh kt hp ListView v Spinner trong bi tp ny lun, nhng v thy n hi phc tp
nn Ti tch ra mt bi tp thc hnh ring, trong bi tp ti bn s hc phn ny.

138

Bi tp 16: Kt hp Spinner vi ListView


trong Android
bi tp 15 bn lm quen c vi Spinner, trong bi tp ny bn s lm mt v d v cch kt
hp gia Spinner vi ListView. Thng th 2 control ny i vi nhau s to thnh cp bi
trng,Spinner dng lu tr danh mc cn ListView lu tr danh sch ca tng danh mc. y
Ti c lm mt v d v qun l sn phm, bn xem hnh:

- Bn quan st hnh Ti chp ng dng, phn trn cng l Danh mc cc sn phm c lu


voSpinner, Khi bn chn vo n th s x ra danh sch nh bn di. khi bn chn danh mc no th
n s load cc sn phm thuc danh mc .
- V d by gi bn chn s 1 l SamSung, n s load ton b sn phm l SamSung vo ListView
bn di:

- Nu bn chn 2- Iphone th n s load ton b sn phm l IPhone vo ListView bn di:


139

- Chng trnh cung cp nt Nhp SP, khi ngi s dng nhp thng tin cho sn phm v nhn nt
ny th chng trnh s lu sn phm vo ng vi danh mc c chn trong Spinner ng thi cp
nht vo ListView bn di.
- Bn cn c ArrayList + ArrayAdapter cho Spinner
- V cn c ArrayList + ArrayAdapter cho ListView
-> Tc l bn phi c 2 cp (4 i tng trn)
- V d ny Ti vit thun hng i tng, v c hi ph cch mt cht so vi quy tc hng i
tng thng thng, l trong lp Sn phm Ti cho php n tham chiu trc tip ti i tng
Danh mc cha n. Nh vy th ng ti danh mc no cng c th ly c ton b danh sch sn
phm ca n, v ng ti mt sn phm bt k no cng bit c n thuc danh mc no.
- Bn xem cu trc chng trnh:

140

- trn bn thy c 3 class: Goods, Product, Catalog: Product v Catalog s k tha


t Goods, Goods s c Id v Name. Sn phm v danh mc cng phi c Id v Name nn n k tha
t Goods l u hp l.
- Bn xem m hnh lp:

-Bn xem cu trc XML cho phn giao din (activity_main.xml):


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:gravity="center"
android:text="Qun l sn phm"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
141

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

android:stretchColumns="*"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Danh mc:" />
<Spinner
android:id="@+id/spDanhmuc"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M Sp:" />
<EditText
android:id="@+id/editId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tn Sp:" />
<EditText
142

77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115

android:id="@+id/editName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="Nhp SP" />
</TableRow>
</TableLayout>
<TextView
android:id="@+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:gravity="center"
android:text="Danh sch sn phm theo danh mc"
android:textColor="#FFFFFF"
android:textSize="15sp" />
<ListView
android:id="@+id/lvsanpham"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

- Tng t nh cc bi tp trc, chng ta phi t id cho cc control. Bi tp ny bn t nhn vo


xem Ti t Id nh th no, Ti khng nhc li na.
- Chng ta ln lt xem ni dung coding ca cc class trong phn x l nghip v:
- 1) Class Goods:
1
2
3
4
5
6

package tranduythanh.com;
/**
* Class ny l class cha ca Product v Catalog
* v Product v Catalog u c Id v Name
* nn Ti to class ny s dng li code
* @author drthanh
143

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

*
*/
public class Goods {
//Id lu m
//Name lu tn
private String id;
private String name;
public String getid() {
return id;
}
public void setid(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Goods(String id, String name) {
super();
this.id = id;
this.name = name;
}
public Goods() {
super();
}
public String toString() {
return this.id+" - "+this.name;
}
}

- 2 class Product:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

package tranduythanh.com;
/**
* Class ny lu thng tin sn phm
* n k th t Goods ly m v tn
* Ti cho n tham chiu ti Catalog
* n c th bit c n thuc danh mc no
* @author drthanh
*
*/
public class Product extends Goods{
//Ly tham chiu lp trnh cho l
private Catalog Dmuc;
public Catalog getDmuc() {
return Dmuc;
}
public void setDmuc(Catalog dmuc) {
Dmuc = dmuc;
}
144

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

public Product(String ma, String name, Catalog dmuc) {


super(ma, name);
Dmuc = dmuc;
}
public Product(String ma, String name) {
super(ma, name);
}
public Product() {
super();
}
}

- 3 class Catalog:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

package tranduythanh.com;
import java.util.ArrayList;
/**
* Class dng lu tr thng tin danh mc
* v danh sch cc sn phm thuc danh mc
* @author drthanh
*
*/
public class Catalog extends Goods {
private ArrayList<Product>listSp=null;
public Catalog(String ma, String name) {
super(ma, name);
this.listSp=new ArrayList<Product>();
}
public Catalog() {
super();
this.listSp=new ArrayList<Product>();
}
/**
* kim tra sn phm tn ti trong danh mc hay cha
* @param p
* @return true nu tn ti
*/
public boolean isDuplicate(Product p)
{
for(Product p1: listSp)
{
if(p1.getid().trim().equalsIgnoreCase(p.getid().trim()))
return true;
}
return false;
}
/**
* thm 1 sn phm vo danh mc
145

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

* thm thnh cng =true


* @param p
* @return
*/
public boolean addProduct(Product p)
{
boolean isDup=isDuplicate(p);
if(!isDup)
{
p.setDmuc(this);
return listSp.add(p);
}
return !isDup;
}
public ArrayList<Product>getListProduct()
{
return this.listSp;
}
public int size()
{
return listSp.size();
}
public Product get(int i)
{
return listSp.get(i);
}
}

- 4 class SpinnerAndListViewActivity x l nghip v trong Activity:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

package tranduythanh.com;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
public class SpinnerAndListViewActivity extends Activity {
Spinner spinDm;
EditText editma,editten;
Button btnNhap;
ListView lvSp;
//cp i tng dng cho Spinner
ArrayList<Catalog> arraySpinner=new ArrayList<Catalog>();
146

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

ArrayAdapter<Catalog>adapterSpinner=null;
//Cp i tng dng cho ListView
ArrayList<Product>arrayListview=new ArrayList<Product>();
ArrayAdapter<Product>adapterListview=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWidgetsControl();
fakeDataCatalog();
addEventsForFormWidgets();
}
/**
* Hm ly cc control theo Id
*/
private void getWidgetsControl()
{
spinDm=(Spinner) findViewById(R.id.spDanhmuc);
editma=(EditText) findViewById(R.id.editId);
editten=(EditText) findViewById(R.id.editName);
btnNhap=(Button) findViewById(R.id.btnInput);
lvSp=(ListView) findViewById(R.id.lvsanpham);
//Cu hnh cho Spinner
adapterSpinner=new ArrayAdapter<Catalog>(this,
android.R.layout.simple_spinner_item,
arraySpinner);
adapterSpinner.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinDm.setAdapter(adapterSpinner);
//Cu hnh cho ListView
adapterListview=new ArrayAdapter<Product>(this,
android.R.layout.simple_list_item_1,
arrayListview);
lvSp.setAdapter(adapterListview);
}
/***
* Hm gi d liu, to 3 danh mc mc nh cho Spinner
*/
private void fakeDataCatalog()
{
Catalog cat1=new Catalog("1", "SamSung");
Catalog cat2=new Catalog("2", "Iphone");
Catalog cat3=new Catalog("3", "IPad");
arraySpinner.add(cat1);
arraySpinner.add(cat2);
arraySpinner.add(cat3);
adapterSpinner.notifyDataSetChanged();
}
/**
* Hm gn s kin cho Button v Spinner
*/
147

79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132

private void addEventsForFormWidgets()


{
btnNhap.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
addProductForCatalog();
}
});
spinDm.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
//mi ln chn danh mc trong Spinner th cp nhp ListView
loadListProductByCatalog(arraySpinner.get(arg2));
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
/**
* Hm thm mt sn phm vo cho danh mc c chn trong
Spinner
*/
private void addProductForCatalog()
{
Product p=new Product();
p.setid(editma.getText()+"");
p.setName(editten.getText()+"");
Catalog c= (Catalog) spinDm.getSelectedItem();
c.addProduct(p);
//Mi ln thm xong th cp nhp li ListView
loadListProductByCatalog(c);
}
/**
* Lc danh sch sn phm theo danh mc v update li ListView
* @param c
*/
private void loadListProductByCatalog(Catalog c)
{
//xa danh sch c
arrayListview.clear();
//ly danh sch mi t Catalog chn trong Spinner
arrayListview.addAll(c.getListProduct());
//cp nht li ListView
adapterListview.notifyDataSetChanged();
}
}
148

- Ti gii thch ngay bn trong m lnh, bn c th c v rng hiu coding Ti vit bn trn.
- Bn c th ti code mu y y: http://www.mediafire.com/?i4lev5ek8944kop
- Bi tp tip theo bn s hc AutoCompleteTextview v MultiAutoCompleteTextview. 2 control
ny bn cht cng ging nh EditText nhng n h tr ngi s dng nhp d liu c nhanh hn,
lm cho ng dng tr ln User Friendly hn, bn hy ch theo di.

149

Bi tp 17: Thc hnh v


AutocompleteTextView
v MultiAutocompleteTextView
- i vi cc thit b di ng, vic h tr nhp d liu nhanh cho ngi s dng l iu rt cn thit.
- Android h tr 2 control ny gip chng ta lm c iu . Bn l danh sch hin th ln n
tng t nh Spinner do mt s bn s tng lm l Spinner khi quan st cha k.
- Ti v d mt trng hp c th nh sau: Bn vit ng dng yu cu nhp vo qu qun, gi s t
nc Vit Nam mnh c 63 tnh thnh, trong c cc tnh nh: H Ni, Hu, H Giang, H Nam
Ninh, bt k tnh no c ch H hoc mt nhm tnh thnh no c cng mt s k t u.
Nh vy ng dng phi Thng minh t a ra li ngh nhp tnh thnh theo ng k t m h
mun nhp, xem hnh di:

- Nh hnh trn: Bn ch cn nhp k t h u tin, n s lc ra cc tnh thnh (hay thnh ph) c k


t u l h.
- Bn nh y khng phi l Spinner v bn nhn vo tng n l Spinner. M n
lAutoCompleteTextView.
- Vy 2 control ny n u? xem hnh:

150

- Bn xem cu trc XML ca giao din (activity_main.xml):


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".AutoCompleteTextViewActivity" >
<TextView
android:id="@+id/selection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#5576BE"
android:text="TextView"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<AutoCompleteTextView
android:id="@+id/editauto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:completionThreshold="1"
android:ems="10" >
<requestFocus />
</AutoCompleteTextView>
<MultiAutoCompleteTextView
android:id="@+id/multiAutoCompleteTextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:completionThreshold="1"
android:ems="10" />
</LinearLayout>

- trn Ti ko 2 control ra lun. V Ti mun demo code ca 2 control ny trong mt ch bn d


so snh.
- Bn nhn vo dng lnh s 21 v 31:
android:completionThreshold= 1
- Mc ch ca n l thit lp s k t bt u lc trong AutoComplete. y Ti nhp l s 1 tc l
ch cn 1 k t l n bt u lc, cn nu nh bn sa thnh 3 th bn nhp ti 3 k t vo n mi bt
u lc.
- Xem class x l (MainActivity.java):
1
2

package tranduythanh.com;
151

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
public class MainActivity extends Activity
implements TextWatcher /*TextWatcher x l s kin
TextChange */
{
TextView selection;
//Khai bo 2 CompleteTextView
AutoCompleteTextView singleComplete;
MultiAutoCompleteTextView multiComplete;
//Khi to mng tm Test
String arr[]={"h ni","Hu","Si gn",
"h giang","Hi an","Kin giang",
"Lm ng","Long khnh"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selection =(TextView) findViewById(R.id.selection);
//ly i tng AutoCompleteTextView ra
singleComplete=(AutoCompleteTextView)
findViewById(R.id.editauto);
//Thit lp lng nghe TextChange
singleComplete.addTextChangedListener(this);
//Thit lp ArrayADapter
singleComplete.setAdapter(
new ArrayAdapter<String>
(
this,
android.R.layout.simple_list_item_1,
arr
));
//Ly i tng MultiAutoCompleteTextView ra
multiComplete=(MultiAutoCompleteTextView)
findViewById(R.id.multiAutoCompleteTextView1);
//Thit lp ArrayADapter
multiComplete.setAdapter(
new ArrayAdapter<String>
(
this,
android.R.layout.simple_list_item_1,
arr
));
//i vi MultiAutoCompleteTextView bt buc phi gi dng
lnh ny
multiComplete.setTokenizer(new MultiAutoCompleteTextView
.CommaTokenizer());
}
//Khi chn trong AutoCompleteTextView hm ny s t ng pht
152

57
58
59
60
61
62
63
64

sinh
public void onTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
selection.setText(singleComplete.getText());
}
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence arg0, int arg1, int
arg2,
int arg3) {
}
}

- Ti gii thch thm:


+ Vic gn DataSource vo ArrayAdapter ri gn ArrayAdapter vo cho ListView nh th no
th n y x nh vy i vi AutoCompleteTextView.
+ i vi MultiAutoCompleteTextView cng vy, n ch yu cu thm dng lnh:
setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer())
- Nh vy nu bn hiu ListView th khng c l do g m li khng hiu CompleteTextView.
- Bn ti code mu y:http://www.mediafire.com/?dos0a2v0bh6hp2b
- Bi tp sau Ti s hng dn cc bn cp nht DataSource lc Runtime
choAutocompleteTextView.

153

Bi tp 18: Cp nht DataSource cho


AutocompleteTextView lc Runtime
- Trong bi tp 17 bn bit cch s
dng AutocompleteTextView vMultiAutocompleteTextView nhng DataSource c c nh
sn trong Coding. Bi tp ny Bn s hc cch cp nht DataSource lc ng dng ang
chy (runtime).
- Ti s c mt v d c th bn thc hnh v trng hp ny, bn hy tp trung theo di v thc
hnh li. Ti ngh bi ny rt th v.
- By gi bn m AVD ln v nhn t hp phm ctrl+ F11 xoay ngang mn hnh, Ti s lm v d
v mn hnh nm ngang.

- Bn xem mn hnh trn Ti chia ra lm 2. Bn tri cho php nhp thng tin sinh vin, bn phi cho
php hin th danh sch sinh vin nhp. Bn ch l ListView Ti lm l Custom Layout (Mi
dng Ln c 2 loi d liu: m v tn cng 1 dng. gii tnh, nm sinh, qu qun cng 1 dng v
ch nh hn c mu in nghing).
- Ngy sinh dng DatePickerDialog
- Ni sinh dng AutoCompleteTextView. Mi ln nhn Nhp Sv th chng trnh s cp nht
ng ni sinh vo DataSource ca n, ch l khng cho php trng lp. Trong cc ln nhp ni
sinh tip theo th n phi t ng lc gip ngi s dng nhp l hn.
- Ta bt u vo chi tit ng dng.
1- y l cu trc th mc trong ng dng:

154

-Nhn vo cu trc th bn thy c 2 Layout, layout chnh l activity_main.xml, cn layout


sinhvien_item_layout.xml l Ti dng custom li ListView (n s c x l trong
classMyArrayAdapter).
2- Thit k giao din vi mn hnh nm ngang (xem hnh):

- Di y l Outline activity_main.xml:

155

- Nu nh nhn vo Outline m bn c th thit k c giao din nh trn th Ti ngh bn tht s


hiu v Layout, tuy nhin Ti vn cung cp Source XML, bn xem tham kho
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFF0E1"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:text="Nhp Thng Tin Sinh Vin:"
android:textColor="#FFFFFF" />
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
156

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M:" />
<EditText
android:id="@+id/editMa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tn:" />
<EditText
android:id="@+id/editTen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gii tnh:" />
<CheckBox
android:id="@+id/chkGt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2"
android:text="L N" />
</TableRow>
157

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140

<TableRow
android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ngy sinh:" />
<EditText
android:id="@+id/editNgaySinh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="date"
android:text="25/09/1989" />
<Button
android:id="@+id/btnNgaySinh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="..." />
</TableRow>
<TableRow
android:id="@+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ni sinh:" />
<AutoCompleteTextView
android:id="@+id/autoCompleteNS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:completionThreshold="1"
android:layout_span="2"
android:ems="10" />
</TableRow>
<TableRow
android:id="@+id/tableRow7"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnNhap"
158

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:gravity="center"
android:text="Nhp SV" />
</TableRow>
</TableLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#EAEAEA"
android:orientation="vertical" >
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000040"
android:text="Danh Sch Sinh Vin:"
android:textColor="#FFFFFF" />
<ListView
android:id="@+id/lvsinhvien"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
</LinearLayout>
</LinearLayout>

- cn y l ca sinhvien_item_layout.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/txtMaVaTen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15sp" />
<TextView
159

15
16
17
18
19
20
21

android:id="@+id/txtThongTinKhac"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#800000"
android:textSize="10sp"
android:textStyle="italic" />
</LinearLayout>

-3 -Bn xem cu trc class x l nghip v:

- class Student:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

package tranduythanh.com;
import java.util.Date;
/**
* Class dng lu tr thng tin ca sinh vin
* id: M
* name: Tn
* gender: gii tnh, true l n
* birthday: lu nm sinh
* placeOfBirth: ni sinh
* @author drthanh
*
*/
public class Student {
private String id;
private String name;
private boolean gender;
private Date birthday;
private String placeOfBirth;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isGender() {
return gender;
160

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

}
public void setGender(boolean gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPlaceOfBirth() {
return placeOfBirth;
}
public void setPlaceOfBirth(String placeOfBirth) {
this.placeOfBirth = placeOfBirth;
}
public Student(String id, String name, boolean gender, Date
birthday,
String placeOfBirth) {
super();
this.id = id;
this.name = name;
this.gender = gender;
this.birthday = birthday;
this.placeOfBirth = placeOfBirth;
}
public Student() {
super();
}
}

- 4 class MyArrayAdapter (class dng Custom Listview):


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

package tranduythanh.com;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
/**
* y l class dng custom layout
* Bn c hc trc
* Class ny s ly layout: sinhvien_item_layout.xml
* @author drthanh
*
*/
public class MyArrayAdapter extends ArrayAdapter<Student> {
161

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

Activity context;
int resourceId;
ArrayList<Student>arrStudent;
public MyArrayAdapter(Activity context, int resource,
ArrayList<Student> objects) {
super(context, resource, objects);
this.context=context;
this.resourceId=resource;
this.arrStudent=objects;
}
@Override
public View getView(int position, View convertView, ViewGroup
parent) {
if(convertView==null)
{
//gn Layout vo Activity
convertView= context.getLayoutInflater().inflate(resourceId,
null);
}
//Ly Textview lu m v tn
TextView txtMaTen=(TextView)
convertView.findViewById(R.id.txtMaVaTen);
//Ly TextView lu gii tnh, nm sinh, ni sinh
TextView txtKhac=(TextView)
convertView.findViewById(R.id.txtThongTinKhac);
//Ly sinh vin th position
Student s=arrStudent.get(position);
txtMaTen.setText(s.getId()+" - "+s.getName());
//Dng SimpleDateFormat nh dng ngy thng dd/MM/YYYY ->
22/12/2012
SimpleDateFormat dft=new
SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
txtKhac.setText((s.isGender()?"N-":"Nam-")+
dft.format(s.getBirthday())+" - "+
s.getPlaceOfBirth());
return convertView;
}
}

-5- class MainActivity x l nghip v:


1
2
3
4
5
6
7
8
9
10
11
12
13

package tranduythanh.com;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.view.Menu;
162

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView lvSinhvien;
//Cp i Custom ListView
MyArrayAdapter adapterSinhvien;
ArrayList<Student> arrSinhvien=new ArrayList<Student>();
EditText editMa,editTen,editNamsinh;
CheckBox chkGender;
Button btnNamsinh,btnNhapsv;
AutoCompleteTextView autoTextNs;
//Cp i dng cho AutoCompleteTextView
ArrayList<String>arrAuto=new ArrayList<String>();
ArrayAdapter<String>adapterAuto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFormWidgets();
addEventsForWidgets();
//fakeData();
}
/**
* hm ly cc widgets
*/
public void getFormWidgets()
{
editMa=(EditText) findViewById(R.id.editMa);
editTen=(EditText) findViewById(R.id.editTen);
editNamsinh=(EditText) findViewById(R.id.editNgaySinh);
chkGender=(CheckBox) findViewById(R.id.chkGt);
autoTextNs=(AutoCompleteTextView)
findViewById(R.id.autoCompleteNS);
btnNamsinh=(Button) findViewById(R.id.btnNgaySinh);
btnNhapsv=(Button) findViewById(R.id.btnNhap);
lvSinhvien=(ListView) findViewById(R.id.lvsinhvien);
//Gn DataSource cho Adapter ListView
adapterSinhvien=new MyArrayAdapter(this,
R.layout.sinhvien_item_layout,
arrSinhvien);
//Gn Adapter vo ListView
163

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

lvSinhvien.setAdapter(adapterSinhvien);
}
/**
* Hm thit lp s kin cho Button
*/
public void addEventsForWidgets()
{
btnNamsinh.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
processBirthday();
}
});
btnNhapsv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
processInput();
}
});
}
/**
* Hm hin th DatePickerDialog chn nm sinh
*/
public void processBirthday()
{
OnDateSetListener callBack=new OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int
arg3) {
editNamsinh.setText(arg3+"/"+arg2+"/"+arg1);
}
};
// y Ti cha x l ly ngy thng nm trn EditText a vo
DatePicker
//Bn t lm
DatePickerDialog dateDialog=new DatePickerDialog(this,
callBack, 1989, 9, 25);
dateDialog.setTitle("Birthday");
dateDialog.show();
}
/**
* Hm x l nhp d liu t giao din
*/
public void processInput()
{
String ma=editMa.getText()+"";
String ten=editTen.getText()+"";
String ns=editNamsinh.getText()+"";
String nois=autoTextNs.getText()+"";
boolean gt=chkGender.isSelected();
SimpleDateFormat dft=new
164

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174

SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
try {
Student s=new Student(ma, ten, gt, dft.parse(ns), nois);
arrSinhvien.add(s);
//Thm mi xong th gi hm di cp nhp li giao din
adapterSinhvien.notifyDataSetChanged();
//X l cho Autocomplete v ni sinh
processAutoComplete(nois);
} catch (ParseException e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
/**
* Hm x l Autocomplete Ni sinh
* @param data
*/
public void processAutoComplete(String data)
{
//Chy t u ch cui nu trng th thot khi hm
for(int i=0;i<arrAuto.size();i++)
{
String x=arrAuto.get(i);
if(x.trim().equalsIgnoreCase(data.trim()))
return;
}
//nu xung y c tc l cha tn ti-> a vo arrAuto
arrAuto.add(data);
//a vo ADapter
adapterAuto=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
arrAuto);
//a Adapter vo AutoComplete
autoTextNs.setAdapter(adapterAuto);
}
public void fakeData()
{
Student s1=new Student("1", "on i Nng", true, new
Date(1980-1900, 2, 2), "TP. H Ch Minh");
Student s2=new Student("2", "Nguyn Thy Trang", true, new
Date(1982-1900, 3, 3), "Lm ng");
Student s3=new Student("3", "Hong Vn Phc", false, new
Date(1970-1900, 4, 4), "H Ni");
Student s4=new Student("4", "inh Hng Li", false, new
Date(1972-1900, 4, 4), "Bc Giang");
Student s5=new Student("5", "Nguyn Hong Uyn", true, new
Date(1970-1900, 4, 4), "Hu");
arrSinhvien.add(s1);
arrSinhvien.add(s2);
arrSinhvien.add(s3);
arrSinhvien.add(s4);
arrSinhvien.add(s5);
adapterSinhvien.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
165

// Inflate the menu; this adds items to the action bar if it is


present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
- Bn xem Ti gii thch trong coding lun ri.
- Ch l bn c th yu cu ng dng chy theo mn hnh nm ngang trong code (bn vit
trongonCreate):
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
- Bn hy c gng lm bi ny v Ti cm thy n rt hay v tng thit k v k thut lp trnh.
- Bn c th Ti code mu ti y: http://www.mediafire.com/?m0jeop2fb83ib3u
- Bi tp tip theo bn s c thc hnh v GridView, mt control cng cn phi lu tm.

166

Bi tp 19: Thc hnh Gridview trong Android


- Bi tp ny bn s lm quen vi control Gridview, cng tng t nh ListView. Gridview cng da
vo Datasource v ArrayAdapter. ListView bn lm nh th no th Gridview y x.
- im khc nhau l GridView c thit lp s ct. D liu lun a vo di dng hnh ng (mng,
list mt chiu), nhng da vo s ct ta thit lp m n t ng ngt hng, xem hnh minh ha:

- Bn thy y, Ti c th hin th Text hoc hnh nh vo GridView.


- Bn c th thit lp s ct cho GridView theo hnh di y:

- Nu bn thit
lp android:numColumns=3, Tc l Gridview s ngt dng khi 3 phn t, n ch khc ch
ny, cn vic a d liu ln nh th no th n y x nh lm vi ListView.
- V d 1: Hin th vn bn ln GridView (xem hnh Ti nh s 1):
- Bn to mt Android Project tn ty thch, y Ti t tn: Vidu_Gridview_Text
- y l activity_main.xml cho ng dng:
1
2
3
4
5
6
7
8
9
10
11
12

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/selection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
167

13
14
15
16
17
18
19
20

android:background="#8A9D6F"
android:hint="Slected here" />
<GridView
android:id="@+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="3" >
</GridView>
</LinearLayout>

- Bn xem dng 15 l id ca GridView, Ti mc nh gridView1


- Dng 18 c thuc tnh: android:numColumns= 3, tc l d liu s c hin th trong Gridview
vi nh dng 3 ct.
- Tip theo bn xem MainActivity.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
public class MainActivity extends Activity {
//Dng mng 1 chiu hoc ArrayList lu mt s d liu
String arr[]={"Ipad","Iphone","New Ipad",
"SamSung","Nokia","Sony Ericson",
"LG","Q-Mobile","HTC","Blackberry",
"G Phone","FPT - Phone","HK Phone"
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Ti tng ny dng hin th phn t c chn trong
GridView
final TextView selection=(TextView)
findViewById(R.id.selection);
final GridView gv=(GridView) findViewById(R.id.gridView1);
//Gn DataSource vo ArrayAdapter
ArrayAdapter<String>da=new ArrayAdapter<String>
(
this,
android.R.layout.simple_list_item_1,
arr
);
//gn Datasource vo GridView
gv.setAdapter(da);
//Thit lp s kin cho GridView,
gv.setOnItemClickListener(new AdapterView
.OnItemClickListener() {
168

37
38
39
40
41
42
43
44
45

public void onItemClick(AdapterView<?> arg0,


View arg1, int arg2,
long arg3) {
//Hin th phn t c chn trong GridView ln TextView
selection.setText(arr[arg2]);
}
});
}
}

- Bn thy , cch s dng GridView l y x nh ListView, nn nu nh bn rnh v ListView


ri th GridView hin nhin bn cng lm tt.
- Thc thi chng trnh bn s thy nh hnh bn di:

- Xem coding y y: http://www.mediafire.com/?v3ww92ys1s5jth0


- V d 2 s phc tp hn, hin th danh sch hnh nh c sn ln GridView, mi ln chn vo
hnh nh no th s hin th chi tit nh trn mt mn hnh mi:
- C th Demo ny c nhiu website v Ebooks lm ri, y Ti cng mun demo li cho cc
bn.
- Bn xem giao din ca ng dng trc:

169

- Bn tri l mn hnh chnh cho php hin th danh sch hnh nh vo GridView, mi ln chn vo
tng hnh trong GridView th s m hnh c chn vo mt mn hnh mi (v d nh khi chn
hnh ch Cu th n s hin th ra nh mn hnh bn phi ), nhn nt Back tr v mn hnh chnh.
- y c mt s khc bit ln l chng ta ch s dng 1 MainActivity, khng h to thm bt
k mt Activity no khc, chng ta ch thay i Layout m thi. Nn n cng l im nhn ca ng
dng.
-Hy to mt Android Project tn: Vidu_Gridview_DisplayImage v xem cu trc ca chng
trnh:

-Layout s c 2 ci: activity_main.xml l ca mn hnh chnh dng hin th danh sch hnh
nh.solo_picture.xml l dng hin th tng hnh ring l.
- To thm th mc drawble v ko th mt s hnh nh vo.
- Phn class c 2 class: MainActivity v MyImageAdapter k tha t BaseAdapter.
- By gi ta i vo chi tit ca tng ci:
- activity_main.xml:

170

- Bn c th nhn vo hnh trn lm hoc ti coding mu bn di.


-solo_picture.xml:

- By gi ta vo cc class x l nghip v:

171

- Th nht l class MyImageAdapter:


+ class ny s k tha t BaseAdapter, v dng hin th tng hnh nh ring l:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

package tranduythanh.com;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
/**
* Class dng hin th tng hnh nh ring l
* @author drthanh
*
*/
public class MyImageAdapter extends BaseAdapter {
private Context mContext;
private Integer []mThumbIds;
public MyImageAdapter(Context c){
mContext=c;
}
public MyImageAdapter(Context c,Integer []arrIds){
mContext=c;
mThumbIds=arrIds;
}
public int getCount()
{
return mThumbIds.length;
}
public Object getItem(int arg0)
{
return null;
}
public long getItemId(int arg0)
{
return 0;
}
/**
* Cn override li hm ny hin th hnh nh
*/
public View getView(int arg0, View convertView, ViewGroup arg2)
{
ImageView imgView;
if(convertView==null){
imgView=new ImageView(mContext);
//can chnh li hnh cho p
imgView.setLayoutParams(new GridView.LayoutParams(85, 85));
172

46
47
48
49
50
51
52
53
54
55

imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setPadding(8, 8, 8, 8);
}else{
imgView=(ImageView) convertView;
}
//ly ng v tr hnh nh c chn
//gn li ImageResource
imgView.setImageResource(mThumbIds[arg0]);
return imgView;
}
}

- Th hai l class MainActivity:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity
implements OnItemClickListener
{
TextView tvMsg;
GridView gv;
TextView tvSoloMsg;
//mng lu danh sch cc id hnh nh c sn
Integer[]mThumbIds;
//Adapter cho GridView
MyImageAdapter adapter=null;
//V khng to thm 1 Activity nn ly lun 2 Id bn
solo_picture.xml
ImageView ivSoloPicture;
Button btnBack;
//Lu Bundle backup cho MainActivity
Bundle myBackupBundle;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Lu savedInstanceState trc vo myBackupBundle
myBackupBundle=savedInstanceState;
setContentView(R.layout.activity_main);
tvMsg=(TextView) findViewById(R.id.tvMsg);
//gn mng cc Id hnh nh cho mThumbIds
mThumbIds=new
Integer[]{R.drawable.image1,R.drawable.image2,
R.drawable.image3,R.drawable.image4,
R.drawable.image5,R.drawable.image6,
R.drawable.ic_launcher,R.drawable.lifecycle};
gv=(GridView) findViewById(R.id.gridView1);
//thit lp Datasource cho Adapter
173

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

adapter=new MyImageAdapter(this, mThumbIds);


//gn Adapter vo Gridview
gv.setAdapter(adapter);
//thit lp s kin m tng hnh nh chitit
gv.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
//gi hm xem hnh nh chi tit ti v tr th arg2
showdetail(arg2);
}
public void showdetail(int posistion)
{
//Khng m Activity mi m ch thit lp li Layout
setContentView(R.layout.solo_picture);
//Va gi hm trn th mn hnh s thay i qua ci mi
//ta ly cc control trong layout mi ny
tvSoloMsg=(TextView) findViewById(R.id.tvSoloMsg);
tvSoloMsg.setText("Image at "+posistion);
ivSoloPicture=(ImageView) findViewById(R.id.imgSolo);
//thit lp hnh nh ang chn ln ImageView mi
ivSoloPicture.setImageResource(mThumbIds[posistion]);
btnBack=(Button) findViewById(R.id.btnBack);
//Thit lp s kin click Back phc hi li
MainActivity
//bng cch gi li onCreate(myBackupBundle);
btnBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
onCreate(myBackupBundle);
}
});
}
}

- Khi chy ng dng bn s c kt qu nh mong mun.


- Bi tp ny bn bit cch s dng GridView, bit cch a hnh nh vo GridView, c bit bit
thm mt k thut mi l thay i Layout i mn hnh khng cn chy Activity.
- Ngoi ra cn bit thm v BaseAdapter.
- Bn c th ti code mu y y: http://www.mediafire.com/?3o2jva4mzgp2kj8
- Bi tp tip theo bn s c thc hnh v TimePickerDialog v DatePickerDialog, 2 control ny
cng ng phi lu tm v n cng dc s dng thng xuyn trong Android.

174

Bi tp 21: Thc hnh v Tab Selector


trong Android
Tab Selector ging nh Property Sheet trong Visual C, ging nh Tab Control C#, hay trong Java:

- Ti s lm mt v d c th v Tab Selector bn c th thc hnh li v hiu c vn .


- i vi Android, mi Tab bn nn thit k trn mt Layout khc nhau, ri trong Main Layout bn
include cc tab vo (Tc l nu nh ng dng bn c 3 Tab con th s to 3 Layout khc nhau ri
include chng vo Main layout, ch ng thit k tt tn tt trong mt Main Layout n s gy kh
khn trong vic sa li ).
- Ti trnh by s qua l thuyt v Tab selector:
+ Tab selector gm c 3 phn: Tab Host, Tab Widgets v FrameLayout.

+Tab Host: L Container chnh cha cc Tab buttons v Tab contents

175

+Tab Widget: nh dng cho cc Tab buttons : Nhn, Icon


+FrameLayout: l Container cha cc layout cho Tab contents, ta ch c th dng FrameLayout
cho Tab contents, khng th dng cc loi Layout khc. Nu bn thc mc ti v sao li l
FrameLayout m khng phi l cc Layout khc? th Ti ch ni n gin th ny: Cho d bn c
nhn vo cc Tab no i na th layout tng ng vi mi Tab m bn va nhn vo cng ch xut
hin cng mt ch trn mn hnh in thoi, iu ny ch c FrameLayout mi gii quyt c.
*** By gi bn hy xem hnh minh ha v giao din trong bi v d Tab Selector ca Ti nh sau:

- Nh hnh trn th bn thy : Tab u tin 1-CALCULATOR l giao din cho php tnh cng
tr nhn chia, Tab th 2 2-HISTORY dng hin th danh sch cc php ton thc hin.
- Bn xem cu trc tng quan ca ng dng:

176

-V ng dng ca Ti c 2 Tab nn Ti s to 2 tabs: tab1_layout.xml v tab2_layout.xml, 2 tabs


ny s c include vo main layout activity_main.xml, vy tng cng Ti c 3 Layout.
- Ta vo xem main layout (activity_main.xml):
- xem Outline d tng tng:

-Cn y l source XML:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TabWidget>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/tab1_layout"/>
</LinearLayout>
<LinearLayout
177

33
34
35
36
37
38
39
40
41
42

android:id="@+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="@layout/tab2_layout"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>

- Bn nhn vo dng lnh 30 v 36:


<include layout=@layout/tab1_layout/>
<include layout=@layout/tab2_layout/>
chnh l cch include mt layout ny vo trong mt layout khc.
- Tip tc ta xem tab1_layout.xml, Ti ly li bi tp trc v cng tr nhn chia:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/TableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="4"
android:background="#5B8020"
android:gravity="center"
android:text="Cng tr nhn chia"
android:textColor="#FFFFFF"
android:textSize="20sp" />
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
178

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="S a:" />
<EditText
android:id="@+id/editsoa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="3"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="S b:" />
<EditText
android:id="@+id/editsob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="3"
android:ems="10"
android:inputType="number" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btncong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+" />
<Button
android:id="@+id/btntru"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-" />
<Button
android:id="@+id/btnnhan"
179

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="*" />
<Button
android:id="@+id/btnchia"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="/" />
</TableRow>
<TableRow
android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/txtketqua"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="4"
android:background="#5B8020"
android:textColor="#FFFFFF"
android:textSize="25sp" />
</TableRow>
</TableLayout>

- V xem tip tab2_layout.xml, n gin l ch c 1 ListView cha danh sch cc php ton thc
hin bn Tab1:
1
2
3
4
5
6
7
8
9
10
11
12
13

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/lvhistory"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

- Gi bn xem MainActivity bit c cch cu hnh Tabhost:


1
2
3
4
5

package tranduythanh.com;
import java.util.ArrayList;
import android.os.Bundle;
180

6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
//Enum thc hin php ton
enum Operator
{
Cong,//php cng
Tru,//php tr
Nhan,//php nhn
Chia//php chia
}
Button btncong,btntru,btnnhan,btnchia;
EditText editsoa,editsob;
TextView txtkq;
ListView lvHistory;
ArrayList<String>array_operator=new ArrayList<String>();
ArrayAdapter<String>adapter=null;
//Variable in listener
OnClickListener myclick=new OnClickListener() {
@Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.btncong:
{
processOperator(Operator.Cong);
}
break;
case R.id.btntru:
{
processOperator(Operator.Tru);
}
break;
case R.id.btnnhan:
{
processOperator(Operator.Nhan);
}
break;
case R.id.btnchia:
{
processOperator(Operator.Chia);
}
}
}
};
181

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

/**
* Hm x l php ton theo operator
* @param op
*/
public void processOperator(Operator op)
{
String sa=editsoa.getText()+"";
String sb=editsob.getText().toString();
int a=Integer.parseInt(sa);
int b=Integer.parseInt(sb);
String kq="";
switch(op)
{
case Cong:
kq=a+" + "+b +" = "+(a+b);
break;
case Tru:
kq=a+" - "+b +" = "+(a-b);
break;
case Nhan:
kq=a+" * "+b +" = "+(a*b);
break;
case Chia:
if(b!=0)
kq=a+" / "+b +" = "+(a*1.0/b);
else
kq="b phai khac 0";
break;
default:
kq="Invalid operator!";
}
txtkq.setText(kq);
array_operator.add(kq);
adapter.notifyDataSetChanged();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadTabs();
doFormWidgets();
}
//Cu hnh tab
public void loadTabs()
{
//Ly Tabhost id ra trc (ci ny ca built - in android
final TabHost tab=(TabHost) findViewById
(android.R.id.tabhost);
//gi lnh setup
tab.setup();
TabHost.TabSpec spec;
//To tab1
spec=tab.newTabSpec("t1");
spec.setContent(R.id.tab1);
spec.setIndicator("1-Calculator");
182

114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156

tab.addTab(spec);
//To tab2
spec=tab.newTabSpec("t2");
spec.setContent(R.id.tab2);
spec.setIndicator("2-History");
tab.addTab(spec);
//Thit lp tab mc nh c chn ban u l tab 0
tab.setCurrentTab(0);
// y Ti s kin ny cc bn ty x l
//V d tab1 cha nhp thng tin xong m li qua tab 2 th
bo...
tab.setOnTabChangedListener(new
TabHost.OnTabChangeListener() {
public void onTabChanged(String arg0) {
String s="Tab tag ="+arg0 +"; index ="+
tab.getCurrentTab();
Toast.makeText(getApplicationContext(),
s, Toast.LENGTH_LONG).show();}
});
}
//Khi to cc i tng v gn ADapter cho ListView
public void doFormWidgets()
{
btncong=(Button) findViewById(R.id.btncong);
btntru=(Button) findViewById(R.id.btntru);
btnnhan=(Button) findViewById(R.id.btnnhan);
btnchia=(Button) findViewById(R.id.btnchia);
editsoa=(EditText) findViewById(R.id.editsoa);
editsob=(EditText) findViewById(R.id.editsob);
txtkq=(TextView) findViewById(R.id.txtketqua);
lvHistory=(ListView) findViewById(R.id.lvhistory);
btncong.setOnClickListener(myclick);
btntru.setOnClickListener(myclick);
btnnhan.setOnClickListener(myclick);
btnchia.setOnClickListener(myclick);
adapter=new ArrayAdapter<String>
(this,
android.R.layout.simple_list_item_1,
array_operator);
lvHistory.setAdapter(adapter);
}
}

- Ti c gii thch s qua trong coding cch to tab, bn hy c gng lm li hiu n.


- Bao nhiu tab khng quan trng, cui cng th cng ch a v x l bnh thng nh ch c 1 mn
hnh.
- Bn c th ti coding mu y: http://www.mediafire.com/?0xyr6ooi066dhiw
- Bi tp k tip bn s hc v Menu v Context menu, 2 control ny rt a chung nn ta phi bit
n.
183

Bi tp 22: Thc hnh v Menu trong Android


- Menu v Context menu l nhng control rt hu dng v n rt c a chung, do chng ta
phi bit v n lm cho ng dng ca Ta t hiu sut cao hn.
- Trc tin Ti s trnh by v Menu:
+ Ty vo tng phin bn Android hay sn phm ca hng sn xut m chc nng hin th menu c
khc nhau cht xu.
+ y Ti ni my o thi, hin th Menu th ta lm nh sau:

- Nu ng dng ca bn c s dng Menu th ch cn click vo nt c ch Menu l s hin th ra.


0) Menu t ng pht sinh khi chng ta to mt Android Project:
- Bn l mi ln to mt Android Project, n s t to cho ta XML menu Resource ng thi
trong MainActivity cng gi sn hm cho chng ta load Menu:

- Nh bn thy th xml resource menu (kin trc bn trong n ta s tnh sau) ca ng dng c lu
trong th mc menu, v mc nhin n cng tn vi Layout.
184

- Bn m MainActivity ln: Thy n override phng thc onCreateOptionsMenu, dng lnh 18,
19 ca Hm ny c dng ti Menu vo ng dng khi ngi dng click vo nt Menu.
1) Cch to Menu:
a) To Menu bng XML resource:
- Gi ti s c tnh hng dn bn to 1 XML menu resource khc ng thi gip bn ti Menu
Resource mi ny vo ng dng khi nhn nt Menu cng nh vit s kin cho cc Menu Item:
+ Bm chut phi vo th mc menu/ chn New / chn Android XML File:

+Mn hnh New Android XML hin ln, ta chn Resource type l Menu ging hnh di y, t
tn cho n l mymenu ri nhn finish:

185

+ Sau khi nhn Finish, bn quan st li th mc menu ca ng dng s xut hin mymenu.xml:

+ to cc Menu Item, bn double click vo mymenu.xml:

+ Mn hnh trn bn
c 2 Tab: Layout v mymenu.xml, Tab Layout cho php bn to menu bng giao din,
tab mymenu.xml cho php bn to menu bng source code xml.
+ By gi ta s lm menu bng giao din, bn nhn vo nt Add pha bn trn :

186

+ mn hnh ny bn chn Item, ri nhn OK:

+ Khi to mt Menu Item th c 2 phn t chnh l Id v Title (Bn xem phn Ti t mu vng).
Ta da vo Id x l coding, bn nn t Id n cho khoa hc, mang tnh gi nh. Nh bn thy ,
Ti t id cho Menu Item ny l item_xemdssv th id ny s c t ng cp nhp vo mn hnh
pha bn tri.
+ Cc thuc tnh khc bn t nghin cu trn mng, hoc khi no gp vn v n Ti s trnh by
sau.
+ C nh vy bn tun t to cho y cc Menu Item m bn mong mun.
*** Trng hp bn mun to Sub Menu Item (Menu Item cha cc Menu Item khc):
+ Ti c to thm 1 Menu Item l Xem danh sch lp, by gi Ti mun to thm 3 Sub Menu
Item cho n, bao gm Lp DHTH1A, Lp DHTH1B v Lp DHTH1C:

*Theo Hnh trn th bn chn Menu bn mun to Sub Menu cho n trc, y l item_xemlop (s
1 Ti nh du)
*Sau bn chn nt Add :
187

- Mc Create a new element at the top level, in Menu to Menu cng cp


- Mc Ti t mu vng Create a element in the selected element to Sub Menu.
* Bm OK tin hnh to Sub Menu, mn hnh sau s xut hin:

+ Tip tc to Menu Item cho Sub Menu ta chn nt Add, mi th s li y x nh to Menu


Item cha ca n vy. Mun xa th chn nt Remove. Khi bn nhn nt Add th bn s thy mn
hnh quen thuc sau:

+ Bn chn la nh trn v nhn OK, c lp li nh vy, mi ln to Menu Item th bn t Id v


Title cho n l xong:

+ Mun thay i th t xut hin ca cc Menu Item bn chn nt Down, Up.


* Nu mun xem XML resource ca n nh th no th bn chn vo tab mymenu.xml:
188

*** By gi bn xem cch gn Menu va to vo ng dng nh th no:


- Bn m MainActivity.java ln:

Dng lnh 13, 14: getMenuInflater().inflate(R.menu.mymenu, menu); dng gn Menu XML


Resource vo ng dng, bn chy my o ln v nhn vo nt Menu, bn s thy c kt qu:

189

+ By gi ta vit Coding x l s kin cho cc Menu Item:


- vit s kin cho cc Menu Item bn cn Override phng thc onOptionsItemSelected, Trong
phng thc ny ta da v Id ca cc Menu Item x l:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater()
.inflate(R.menu.mymenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.item_xemdssv:
//X l xem danh sch sinh vin
break;
case R.id.item_lopdhth1a:
//x l xem thng tin lp DHTH1A
break;
case R.id.item_lopdhth1b:
break;
case R.id.item_lopdhth1c:
break;
}
return super.onOptionsItemSelected(item);
190

34
35

}
}

- Bn nhn vo dng lnh 19 tr xung, y Ti dng switch case x l theo ng Id m ngi


s dng chn la. Ty vo yu cu ca bi ton m chng ta x l trong ny. Ti khuyn bn nn
vit tng hm ring theo nghip v ri c th m gi hm theo ng Menu Item.
- Bn ti code mu y: http://www.mediafire.com/?zawcff1ha6ap3ic
b) To Menu bng Coding (Runtime):
- Chng ta c th to Menu lc Runtime (khng cn dng XML Resource):
1
2
3
4
5
6
7
8
9

public boolean onCreateOptionsMenu(Menu menu) {


menu.add("Menu 1");
menu.add("Menu 2");
SubMenu sub3= menu.addSubMenu("Menu 3");
sub3.add("File 1 Menu 3");
sub3.add("File 2 Menu 3");
sub3.add("File 3 Menu 3");
return true;
}

- Bn nhn thy y, vic to Menu lc Runtime rt d dng. Nhng nu nh bn vit code to Menu
nh vy th vic x l gp cht kh khn v bn khng bit Id ca mi Menu Item.
- Do bn nn vit li theo cch sau:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//i s 1 l nhm
//i s 2 l Id cho Menu Item
//i s 3 l th t xut hin ca Menu Item
//i s 4 l tiu cho Menu Item
int itemId=113;
menu.add(0, itemId, 0, "Menu 1");
191

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

itemId=114;
menu.add(0,itemId,1,"Menu 2");
SubMenu sub3= menu.addSubMenu("Menu 3");
itemId=115;
sub3.add(0,itemId,0,"File 1 Menu 3");
itemId=116;
sub3.add(0,itemId,1,"File 2 Menu 3");
itemId=117;
sub3.add(0,itemId,2,"File 3 Menu 3");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case 113:
//X l Menu 1
break;
case 114:
//X l Menu 2
break;
case 115:
//X l File 1 ca Menu 3
break;
case 116:
//X l File 2 ca Menu 3
break;
case 117:
//X l File 3 ca Menu 3
break;
}
return super.onOptionsItemSelected(item);
}
}

- Nh vy mi ln to Menu Item bn nn gn Id cho n v x l theo Id ny trong


hm onOptionsItemSelected.
- Bn ti code mu y: http://www.mediafire.com/?em82rb51dduvnou
- Bi tp ny Ti s khng lm v d mu ln, Ti dnh khi hc xong Context Menu Ti Demo
lun.
- Bi tp sau Ti s hng dn cch lm Context Menu.

192

Bi tp 23: Thc hnh v Context Menu


trong Android
Tip ni bi 22, Bi tp ny bn s hc v Context Menu mt trong nhng control hu dng m
Android cung cp.
- i vi C# , VB, hay Java hin th Context Menu : Sau khi thit lp Context Menu ta ch cn
bm chut phi vo i tng th s c Menu Popup ra theo ng yu cu.
- i vi Android: Chng ta cng phi ng k Context Menu cho i tng sau mun hin th
ln th ta nhn tht lu vo i tng (long click ).
- Tng t nh vi Menu, Ta c th to Context menu trong XML hoc trong Coding.
- Cch to Context Menu bng XML th n y x nh Menu khng khc 1 t ADN no c, nn
Ti s khng ni li cch to trong XML. M Ti s ni lun cch ng k Context Menu cho i
tng cng nh cch x l s kin cho tng Menu Item trong Context Menu.
- y Ti lm mt v d n gin v Context Menu. Giao din c 1 Button, khi nhn tht lu vo
n th s hin th Context Menu cho php i mu ch : Mu , mu xanh l cy v xanh dng:

- hnh trn l khi Context Menu hin th ra, Ti chn Red > Mu ca Button s chuyn thnh mu
.
- Bn xem cu trc th mc ca Project ny v ni dung bn trong ca Context menu:

193

- Tip tc bn Double click vo strings.xml , Ti c nh ngha mt s color trong ny:

- trong strings.xml , Ti to 3 tag color : Red, Green, Blue; Ni dung bn phi dng Hex Color.
3 mu ny s c triu gi trong hm x l s kin khi ngi s dng chn tng Menu Item trong
Context Menu.
- Bn xem ni dung MainActivity.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
public class MainActivity extends Activity {
Button btnCtx;
@Override
protected void onCreate(Bundle savedInstanceState) {
194

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCtx=(Button) findViewById(R.id.btnshowcontext);
registerForContextMenu(btnCtx);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater()
.inflate(R.menu.my_context_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.itemRed:
btnCtx.setTextColor(
getResources().getColor(R.color.clrred));
break;
case R.id.itemGreen:
btnCtx.setTextColor(
getResources().getColor(R.color.clrgreen));
break;
case R.id.itemBlue:
btnCtx.setTextColor(
getResources().getColor(R.color.clrblue));
break;
}
return super.onContextItemSelected(item);
}
}

- Bn quan st dng lnh:


+ Dng lnh 22 , onCreateContextMenu dng np Context Menu XML vo ng dng
+ Dng lnh 30, onContextItemSelected dng x l s kin.
+ ng k Context Menu cho i tng no th bn lm ging nh dng
19: registerForContextMenu(btnCtx);
+ getResources().getColor(R.color.clrred) dng ly mu t XML Resource
+ Nh vy bn bit cch s dng Context Menu
+ Bn c th ti coding mu y: http://www.mediafire.com/?8s368sl4z594y85
- Bi tp sau cc bn s thc hnh v Intent, Intent l linh hn ca Android, n l ht nhn chnh
trong Android, cc bn ch theo di.
195

Bi tp 24: Thc hnh v Intent trong Android


- Cc bn i qua c cc thnh phn giao din trong Android, bi tp ny cc bn s lm quen
vi Intent. Intent rt quan trng n l linh hn ca Android, l ht nhn Android tn ti, hu nh
mi th trong Android u c du n ca Intent.
- Cc bn cn hiu r Intent, Ti s a ra hng lot v d t d ti kh cc bn c th thm thu
n t t.
- i vi ngi bt u tip cn Android th Ti c th ni rng cc bn ch dng Intent m cc
Activity v truyn d liu qua li gia chng m thi. Khi nng cao level th bn s s dng Intent
nhng mc ch khc nhau (Ti s c nhng v d ring v n, nhng trc tin cc bn ch cn s
dng tt trong vic m Activity v x l tc v ny tt l ok ri).
- V l do , ph hp vi cc bn th Ti chia Intent ra lm 2 cng dng chnh:
1) Dng Intent m mt Activity khc nhng khng kim sot kt qu tr v.
2) Dng Intent m mt Activity khc v c kim sot kt qu tr v.
By gi chng ta vo tng v d c th:
V d 1: n thun l m mt Activity khc.

- Ti gii thch
hnh trn nh sau: T Main Activity Ti c 1 Button, khi nhn vo Button ny th s m mt Activity
khc, ti Activity mi m ny s c 1 Button cho php quay tr li MainActivity.
- Bn phi nh li vng i ca mt ng dng Android bi tp 5 v bi tp 6 lm v d ny tt
hn.
- Bn to mt Android Project c cu trc nh hnh bn di:

196

- Bn ch l mi Activity mun c triu gi trong Android th phi ng k trong Manifest,


cc bi tp trc Ti cng ni ri, nhng Ti vn nhc li AndroidManifest.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="tranduythanh.com"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" >
</uses-sdk>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="tranduythanh.com.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="tranduythanh.com.ChildActivity"
android:label="@string/title_activity_child" >
</activity>
</application>
</manifest>

- Bn thy c MainActivity (dng 16) v ChildActivity (Dng 24) u phi c ng k trong


Manifest.

197

- Gi ta xem giao din v cch x l coding trong MainActivity:

- y l cu trc XML ca activity_main.xml trn:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#008000"
android:gravity="center"
android:text="This is main Activity"
android:textColor="#FFFF00"
android:textSize="20sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnOpenChildActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Open Child Activity" />
</LinearLayout>

- Tin hnh xem coding MainActivity.java:


1
2
3
4
5
6
7
8

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
198

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

public class MainActivity extends Activity {


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnOpen=(Button)
findViewById(R.id.btnOpenChildActivity);
btnOpen.setOnClickListener(new
View.OnClickListener() {
public void onClick(View arg0) {
doOpenChildActivity();
}
});
}
public void doOpenChildActivity()
{
Intent myIntent=new Intent(this, ChildActivity.class);
startActivity(myIntent);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if
it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

- Quan st dng lnh 25:


Intent myIntent=new Intent(this, ChildActivity.class);
i s 1 l context hin ti, nu bn mun chc n u n cng hiu th bn gn tn class Activity
nh th ny:
Intent myIntent=new Intent(MainActivity.this, ChildActivity.class);
Vi MainActivity l mt Activity ty (trong Context hin ti), vit nh trn th bn s lun lun
ng trong mi trng hp.
i s 2 l : ChildActivity.class, Tc l bn mun m Activity no th ly tn Activity .class;
trong trng hp ny Ti mun m ChildActivity nn Ti ghi l ChildActivity.class
- Quan st dng lnh 26
startActivity(myIntent); Hm ny c tc dng m Activity c truyn vo i s th 2 trn.
- Tin hnh khm ph ChildActivity:

199

-y l source XML ca ChildActivity:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ChildActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#FFFF00"
android:gravity="center"
android:text="This is Child Activity"
android:textColor="#008040"
android:textSize="20sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnBacktoMainActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Back to Main Activity" />
</LinearLayout>

-Giao din ca ChildActivity ch c mt Button cho php quay li MainActivity.


- Bn xem coding ca ChildActivity:
1
2
3
4
5
6
7
8
9

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class ChildActivity extends Activity {
200

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child);
Button btnBack= (Button)
findViewById(R.id.btnBacktoMainActivity);
btnBack.setOnClickListener(new
View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.activity_child, menu);
return true;
}
}

-Dng lnh 18: finish() c nhim v ng Activity hin ti.


- Bn va i qua 1 v d v cng n gin.
- Ti coding y:http://www.mediafire.com/?awoq5mkffm00qes
V d 2: M mt Activity khc ng thi truyn d liu qua.
- Bn xem hnh Ti minh ha di ny:

- y Ta thng dng i tng Bundle ng gi d liu truyn ti qua cc Activity khc.


- Ti sao li nn dng Bundle truyn ti d liu qua li gia cc Activity?
+ Ti ly v d sau: Gi s bn phi chuyn ton b hng ha t Vit Nam sang Singapore, trng
hp ny Ta s b tt c cc hng ha vo trong 1 Container ri chuyn Container ny i, Khng phi
chuyn tng mn hng 1 qua Singapore. Tng t nh vy, i vi Android khi truyn d liu chng
ta cng c th truyn tng thng s ring l nhng chng ta khng nn, chng ta phi b tt c cc d
liu ring l vo 1 Bundle ri gi Bundle ny qua Activity no . Bn kia ch cn ly Bundle ny
ra, mi d liu u nm trong Bundle v ta d dng x l.
201

- Bundle c 2 loi phng thc: putXXX dng cho bn gi i, ng vi kiu d liu no th put
ng kiu . v d trn putInt v putDouble l tng ng vi 2 loi d liu khc nhau (phi i km
vikey bn nhn c th x l ng)
- bn nhn Bundle th dng cc phng thc getXXX tng ng ly d liu theo key bn gi.
- key ny phi ging nhau cho c 2 ni. Ni nhn t key=soa th bn nhn cng phi dng key=soa.
- Ta cng c th truyn i Tng qua li gia cc Activity, cc i tng ny phi c Serialize

- Trong trng hp truyn i tng th ta dng putSerializable v getSerializable


- Ti s lm mt v d n gin vi giao din nh bn di:

202

- T MainActivity c 2 thng s l a v b. Khi nhn nt Kt qu n s truyn 2 thng s ny qua


ResultActivity v tin hnh gii phng trnh bc 1. Mun tr v tip tc gii phng trnh khc
khi nhn nt Back.
- Bn xem cu trc chng trnh d x l:

- Bn xem giao din ca MainActivity (activity_main.xml):

- y l Source XML ca MainActivity:


1
2
3
4
5
6
7
8
9
10
11
12

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
203

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

android:layout_gravity="center"
android:background="#008040"
android:gravity="center"
android:text="Gii phng trnh bc 1"
android:textColor="#FFFF00" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#E5E5E5"
android:text="Nhp a:" />
<EditText
android:id="@+id/txta"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#E5E5E5"
android:text="Nhp b:" />
<EditText
android:id="@+id/txtb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10" />
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<Button
android:id="@+id/btnketqua"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
204

67
68
69
70
71

android:layout_column="1"
android:text="Kt qu" />
</TableRow>
</TableLayout>
</LinearLayout>

- Trong xml layout Bn c th chn layout no cng c, trn Ti dng TableLayout


- Tin hnh xem coding ca MainActivity.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText txta,txtb;
Button btnketqua;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txta=(EditText) findViewById(R.id.txta);
txtb=(EditText) findViewById(R.id.txtb);
btnketqua=(Button) findViewById(R.id.btnketqua);
btnketqua.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//To Intent m ResultActivity
Intent myIntent=new Intent(MainActivity.this,
ResultActivity.class);
//Khai bo Bundle
Bundle bundle=new Bundle();
int a=Integer.parseInt(txta.getText().toString());
int b=Integer.parseInt(txtb.getText().toString());
//a d liu ring l vo Bundle
bundle.putInt("soa", a);
bundle.putInt("sob", b);
//a Bundle vo Intent
myIntent.putExtra("MyPackage", bundle);
//M Activity ResultActivity
startActivity(myIntent);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
205

- Ti gii thch m lnh trong on code trn ri.


- dng 31, key nhn dng Bundle l MyPackage, bn ResultActivity s da vo key ny ly
Bundle ra.
- Sau khi c Bundle ri th da vo soa, sob dng lnh 28,29 ly ng d liu.
- By gi ta qua giao din ResultActivity:

- Bn xem XML Resource ca ResultActivity:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ResultActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Kt qu gii phng trnh bc 1" />
<TextView
android:id="@+id/txtketqua"
android:layout_width="match_parent"
android:layout_height="50sp"
android:gravity="center"
android:background="#CCFFD9"
/>
<Button
android:id="@+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Back" />
</LinearLayout>
206

- Tip tc xem x l coding ca ResultActivity:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

package tranduythanh.com;
import java.text.DecimalFormat;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ResultActivity extends Activity {
TextView txtketqua;
Button btnBack;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
btnBack=(Button) findViewById(R.id.btnBack);
txtketqua=(TextView) findViewById(R.id.txtketqua);
//ly intent gi Activity ny
Intent callerIntent=getIntent();
//c intent ri th ly Bundle da vo MyPackage
Bundle packageFromCaller=
callerIntent.getBundleExtra("MyPackage");
//C Bundle ri th ly cc thng s da vo soa, sob
int a=packageFromCaller.getInt("soa");
int b=packageFromCaller.getInt("sob");
//tin hnh x l
giaipt(a, b);
btnBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
public void giaipt(int a,int b)
{
String kq="";
if(a==0 && b==0)
{
kq="V s nghim";
}
else if(a==0 && b!=0)
{
kq="V nghim";
}
else
{
DecimalFormat dcf=new DecimalFormat("0.##");
kq=dcf.format(-b*1.0/a);
}
txtketqua.setText(kq);
207

53
54
55
56
57
58
59
60
61

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

-Bn xem dng lnh 22: Intent callerIntent=getIntent(); lnh ny cho php ly Intent start Activity
ny. Tc l ly Intent m ta khai bo bn MainActivity start ResultActivity.
- C c Intent ny ri th mi th bn lm nh Ti gii thch trong Coding trn.
- Bn c th ti coding mu y:http://www.mediafire.com/?vb8ddcoos7dupv7
V d 3: M mt Activity khc ng thi truyn d liu qua v x l kt qu tr v.
- V d ny bn s bit cch x l kt qu tr v nh th no.
- Bn xem hnh minh ha:

- Chng ta s da vo requestCodeID v resultCode x l.


- Vic to Intent trong trng hp ny cng y x nh trng hp trc. N ch khc hm gi :

- V phi thm hm x l kt qu tr v:

208

- Ti lm v d sau bn d hiu:
- Chng trnh n gin l MainActivity s c 1 Button v ListView nh hnh bn di:

- Khi nhn M Activity nhp d liu, chng trnh s m Activity mi di dng Dialog:

- Khi nhp s v nhn Lu bnh phng th n s truyn s ny qua MainActivity v cp nht


ListView vi s ny l nhn bnh phng.
- Khi nhp s v nhn lu s gc th n s truyn s ny qua MainActivity v cp nht ListView
vi ng s gc ny.
- Bn ch l phi ng Dialog ngay, v nu khng ng th onActivityResult s khng sy
ra. onActivityResult ch sy ra trong foreground life time.
- Ta tin hnh khm ph ng dng:
209

- Xem cu trc chng trnh:

- Source XML ca Mainactivity:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/btnopenactivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="M Activity Nhp D Liu" />
<ListView
android:id="@+id/lvdata"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

- Source XML ca activity_input_data.xml:


1
2
3
4

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
210

5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".InputDataActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nhp s:" />
<EditText
android:id="@+id/editNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnSave1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Lu Bnh Phng" />
<Button
android:id="@+id/btnSave2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Lu S gc" />
</LinearLayout>
</LinearLayout>

- Nh l phi cu hnh InputDataActivity di dng Dialog: M Manifest cu hnh nh hnh bn


di:

211

- chn Theme: @android:style/Theme.Holo.Dialog


-Ti mn hnh trn ta chn ng Activity mun lm Dialog ri tm ti thuc tnh Theme, nhn vo
nt Browse:

-By gi bn xem x l code ca MainActivity.java:


1
2
3
4
5
6
7
8
9
10
11

package tranduythanh.com;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
212

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

import android.widget.ListView;
public class MainActivity extends Activity {
public static final int REQUEST_CODE_INPUT=113;
public static final int RESULT_CODE_SAVE1=115;
public static final int RESULT_CODE_SAVE2=116;
Button btnInputData;
ListView lvData;
ArrayList<Integer>arrData=new ArrayList<Integer>();
ArrayAdapter<Integer>adapter=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnInputData =(Button) findViewById(R.id.btnopenactivity);
btnInputData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//M Activity vi REQUEST_CODE_INPUT
Intent intent=new Intent(MainActivity.this,
InputDataActivity.class);
//gi startActivityForResult
startActivityForResult(intent, REQUEST_CODE_INPUT);
}
});
//on code di ny hc nhiu ri, ko ni li
lvData=(ListView) findViewById(R.id.lvdata);
adapter=new ArrayAdapter<Integer>
(this,
android.R.layout.simple_list_item_1,
arrData);
lvData.setAdapter(adapter);
}
/**
* X l kt qu tr v y
*/
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//Kim tra c ng requestCode =REQUEST_CODE_INPUT hay khng
//V ta c th m Activity vi nhng RequestCode khc nhau
if(requestCode==REQUEST_CODE_INPUT)
{
//Kim tr ResultCode tr v, ci ny bn InputDataActivity
truyn v
//c n ri th x l tr ln thng thng
switch(resultCode)
{
case RESULT_CODE_SAVE1:
//gi tr t InputDataActivity
int v1= data.getIntExtra("data", 0);
213

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

arrData.add(v1*v1);
adapter.notifyDataSetChanged();
break;
case RESULT_CODE_SAVE2:
//gi tr t InputDataActivity
int v2= data.getIntExtra("data", 0);
arrData.add(v2);
adapter.notifyDataSetChanged();
break;
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

- Chng ta nn khai bo hng s cho RequestCode v ResultCode nh trn, da vo n chng ta


x l kt qu tr v.
- Bn qua x l code ca InputDataActivity.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class InputDataActivity extends Activity {
Button btnSave1,btnSave2;
EditText editNumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input_data);
btnSave1=(Button) findViewById(R.id.btnSave1);
btnSave2=(Button) findViewById(R.id.btnSave2);
btnSave1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//Gi thng ip l lu bnh phng
sendToMain(MainActivity.RESULT_CODE_SAVE1);
214

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

}
});
editNumber=(EditText) findViewById(R.id.editNumber);
btnSave2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//Gi thng ip l lu s gc
sendToMain(MainActivity.RESULT_CODE_SAVE2);
}
});
}
/**
* hm x l gi kt qu v mainactivity
* khi hm ny c gi th lp tc onActivityResult
* MainActivity s sy ra em theo ResultCode v Intent
* @param resultcode
*/
public void sendToMain(int resultcode)
{
Intent intent=getIntent();
int value= Integer.parseInt(editNumber.getText()+"");
intent.putExtra("data", value);
setResult(resultcode, intent);
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.activity_input_data, menu);
return true;
}
}

- Bn nhn vo hm sendToMain, khi hm ny va kt thc th lp tp onActivityResult ca


MainActivity s sy ra
onActivityResult(int requestCode, int resultCode, Intent data)
Ta kim tra requestCode v resultCode cho ng
requestCode l bn MainActivity dng triu gi mt Activity bt k no
resultCode l kt qu tr v trong hm setResult(resultcode, intent); ca sub Activity no . Hm
ny cho chng ta bit kt qu tr v l code no v ng thi cho ta bit lun Intent ca n. Da vo
Intent ny m trong onActivityResult ta c th d dng ly thng s ra (i s th 3).
- Nh vy bn bit s qua v Intent, bn phi li i lm li 3 v d ca Ti va nu ra bn trn.
- Trong bi tp tip theo, Ti s cng c kin thc Intent cho bn bng mt v d c th y v hi
kh v Intent, bn hy ch theo di.
215

- Bn c th ti code mu y y: http://www.mediafire.com/?d8if4q9asgso18q

Bi tp 25: Tip tc cng c kin thc Intent, v


d tng hp Qun L Nhn Vin
- bi tp 24 bn hiu c bn v Intent
- Bi tp ny Ti ch vit tht phc tp ln cc bn tp trung cng lc tm hiu n.
- Xin li v cc bn ch lu mi cp nht bi tp ny.
- By gi Ti tip tc hng dn cc bn tm hiu su v Android cng nh n tp li cc thnh phn
hc trc .
- Bi tp ny Ti cng ch gii thch t i (v gii thch qu nhiu cc bi tp trc ri). Bi tp
ny bn phi tp suy lun logic hiu n su hn.
- Ti tin chc rng nu nh bn hiu bi tp 25 ny th bn c th vit c mt chng trnh
Android ra tr ri. V n l tng hp ca cc kin thc v Android m Ti trnh by t trc ti
gi.
- Mc tiu ca bi tp ny:

- Thao tc nhun nhuyn vi Intent


- n tp li cc control thng hay s dng
- Nhun nhuyn vi ListView
- X l Checked (radio, Checkbox) trong ListView
- Nhun nhuyn vi Custom Layout
- Bit cch s dng Enum
- Cch s dng chung Layout cho cc Activity
- v n nhn thm mt s tng sng to trong lp trnh.

- Bi ny rt l kh v phc tp, nhng i li n rt hay. Ti hi vng bi tp ny s gip ch cho cc


bn rt nhiu trong vic khm ph Android. V vy Ti khuyn cc bn hy chm ch lm i lm
li bi ny.
216

- M t chng trnh:
+ Chng trnh cho php qun l nhn vin + phng ban.
+ Mi phng ban s c nhiu nhn vin, phng ban cn lu tr (m phng ban, tn phng ban)
+ Mt phng ban s c Trng phng v Ph phng. Trng phng th ch c 1, ph phng th s
lng khng gii hn (hoc khng c)
+ Thng tin nhn vin : M nhn vin, tn nhn vin, gii tnh (nam, n), chc v (trng phng,
ph phng, nhn vin)
+ Chng trnh cho php:

Thm/sa/ xa phng ban


Thm / sa / xa nhn vin
cho php nhn vin chuyn phng ban
cho php thit lp ban lnh o phng ban (trng ph)
v mt s chc nng khc

Sau y l demo giao din chnh ca chng trnh:

- Ti gii thch v mn hnh chnh nh sau:


+ Nt Lu Phng Ban: Cho php lu phng ban v cp nht vo ListView. Nu m phng ban
tn ti th t ng cp nht, cn m phng ban cha tn ti th phi thm mi.
+ S kin nhn trn ListView: nhn vo phng ban no th hin th li thng tin ca phng ban
vo phn edittext bn trn.
+ ListView phi s dng Custom Layout, Ta phi t thit k Layout cho ListView bn trn:
217

* Mi phn t ListView c cha 2 TextView, TextView 1 dng hin th m phng ban v tn


phng ban, ch phi cho ngi s dng bit Phng ban ny c nhn vin hay cha c, nu c nhn
vin th c bao nhiu ngi (xem hnh trn).
* Mi phng ban phi cho bit Trng Phng v ph phng l ai (xem hnh)
* V d bn nhn vo phng K Thut: Bn thy thng tin phng ban v s nhn vin trong phng
ban l 3. V Trng Phng tn l on i Nng. C 2 Ph Phng l Trn o c v
Nguyn i Ti.
*Phng dch v th cha c nhn vin no c
*Phng Truyn Thng th c 3 nhn vin nhng ch c 1 trng phng l Nguyn Th To.
- Tip tc x l Context Menu cho ListView Phng ban:

- Khi nhn tht lu vo mt phng ban no , v d trng hp trn l phng K Thut, chng
trnh s hin th context Menu c 4 chc nng:
1. Thm nhn vin
2. Xem danh sch nhn vin
3. Lp trng/ ph phng
4. v xa phng ban.
- ng vi mi chc nng ta c:
1. Thm nhn vin:
- Mc nh mi mt nhn vin mi c to ra th ch c chc v l Nhn Vin (khng c chc qun
l):
218

- Nt xa trng : cho php xa d liu trn EditText v focus ti m nhn vin


- Nt Lu nhn vin, cho php thm mi nhn vin vo phng ban, Gii Tnh Nam, N hin th
hnh nh cho ng.
- Sau khi bm nt Lu nhn vin, th cp nht li danh sch phng ban (cp nhp s lng nhn
vin cho phng ban).
- V d hnh trn by gi Ti bm Lu nhn vin, mn hnh ny s tt i hin th li mn hnh
chnh, nhng trong phng ban K Thut s lng nhn vin s tng ln l 4, xem hnh:

2. Xem danh sch nhn vin:


- Chng trnh s hin th danh sch nhn vin ca phng ban ang chn, v d trong trng hp ny
l xem danh sch nhn vin ca phng ban K thut:

- Nh bn thy . Mn hnh xem danh sch nhn vin c cc chc nng sau:
219

+ Nt mi tn BacK cho php tr v mn hnh chnh.


+Nhn vin c hnh theo gii tnh (nam, n)
+ Nhn vin c m t: Chc v, gii tnh
+ Vy ta cng phi dng Custom layout
- By gi ta xem chc nng Context Menu cho ListVew ca mc xem danh sch nhn vin:

- Vy mn hnh ny c 3 chc nng:


2.1 Sa nhn vin
2.2 Chuyn phng ban
2.3 xa nhn vin
- Ta vo tng chc nng:
2.1 Sa nhn vin:
- v d trn l ta nhn tht lu vo nhn vin tn Trn o c, sau Context Menu hin th
ln, ta chn sa nhn vin, mn hnh sa xut hin nh sau (ch l Activity sa nhn vin s dng
chung Layout vi Activity thm nhn vin):

220

- Thng tin ca nhn vin Trn o c s c hin th nh trn. M nhn vin s cm thay i,
cn cc chc nng khc l y x nh trong mn hnh thm mi nhn vin.
- Trong trng hp ny Ti sa Trn o c thnh Trn Th v nhn nt Lu nhn vin th
mn hnh ny ng li tr v mn hnh xem danh sch, bn quan st s thay i nh sau:

2.2 Chuyn phng ban:


- By gi ta vo chc nng chuyn phng ban cho nhn vin. Chng trnh s hin th danh sch
phng ban (c RadioButton bn cnh cho php chuyn phng ban).
- By gi Ti chn Trn Th v chuyn qua phng Dch v (Nhn tht lu vo Trn Th, context
menu hin th ra th ta chn Chc nng Chuyn phng ban):

- Sau khi chn phng ban chuyn, nhn nt c hnh Apply, chng trnh s quay li mn hnh
xem danh sch nhn vin, lc ny Bn khng cn thy nhn vin Trn Th na, bi v nhn vin ny
c chuyn qua phng dch v:

221

- Bn c th kim tra li bng cch bm nt Back tr v mn hnh chnh, trong mn hnh chnh
s xut hin 1 nhn vin m ta va chuyn:

2.3 xa nhn vin


- by gi ta qua chc nng Xa nhn vin trong mn hnh xem danh sch, chng trnh s hin th
mn hnh hi xem c chc chn mun xa hay khng? nhn ng xa:
- V d Ti chn nhn vin tn Trn Duy Thanh ri xa:

3. Lp trng/ ph phng:
222

- by gi ta qua chc nng Lp trng / ph phng cho mi phng ban (ti mn hnh chnh).
- Khi context Menu hin th ln th ta chn Lp trng. ph phng:
- V d, by gi Ti nhn tht lu vo phng ban Truyn Thng, sau Ti thit lp trng ph
phng li cho phng ban ny, xem giao din bn di:

- Sau khi chn lp trng/ ph phng, th chng trnh hin th mn hnh thit lp nh bn di:

- Trng phng th ch cho php chn 1 (dng Radio Button)


- Ph phng cho php chn ty (dng Checkbox)
- Ta dng layout c sn ca android (khng phi custom layout), ch vit li s kin onclick cho
ListView n hiu m thi.
- Sau khi chn Trng/ ph, click Apply th chng trnh tr v mn hnh chnh, quan st:

223

- Bn thy , Trng phng v ph phng c cp nht.


4. v xa phng ban.
- Ta qua chc nng cui cng: Xa phng ban, tng t nh xa nhn vin. CHng trnh cng hi
ta c chc chn mun xa hay khng?

- Nh vy Ti m t xong yu cu ca bi ton. By gi Ti i chi tit vo coding:


- Bn xem cu trc th mc ca Android Project:

224

225

- Bn quan st trong phn Source Code Ti chia ra lm 3 Package:


1) tranduythanh.com.model -> dng vit m hnh ha i tng
2) tranduythanh.com.adapter -> dng vit Customlayout cho ListView
3) tranduythanh.com.activity > dng lu tr cc Activity
- By gi ta vo package : tranduythanh.com.model :

- Package ny c 3 class v 1 enum chc v (thc ra enum cng l mt class c bit).


- Coding enum ChucVu.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

package tranduythanh.com.model;
/**
* Enum ny thit lp chc v cho nhn vin
* @author drthanh
*
*/
public enum ChucVu {
//Mun gn c nh th ny: TruongPhong("Trng Phng")
//th phi c constructor ChucVu(String cv)
TruongPhong("Trng Phng"),
PhoPhong("Ph Phng"),
NhanVien("Nhn Vin");
private String cv;
ChucVu(String cv)
{
this.cv=cv;
}
public String getChucVu()
{
return this.cv;
}
}

- Coding Infor.java:
1
2
3
4
5
6

package tranduythanh.com.model;
import java.io.Serializable;
/**
* Class ny lu m v tn l class cha ca NhanVien
* v PhongBan. V c nhn vin hay phng ban u c m v
226

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

tn
* @author drthanh
*
*/
public class Infor implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String ma;
private String ten;
public Infor(String ma, String ten) {
super();
this.ma = ma;
this.ten = ten;
}
public Infor() {
super();
}
public String getMa() {
return ma;
}
public void setMa(String ma) {
this.ma = ma;
}
public String getTen() {
return ten;
}
public void setTen(String ten) {
this.ten = ten;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.ma+" - "+this.ten;
}
}

- Coding NhanVien.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14

package tranduythanh.com.model;
import java.io.Serializable;
/**
* Class lu tr thng tin nhn vin
* @author drthanh
*
*/
public class NhanVien extends Infor implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private boolean gioitinh;
private ChucVu chucvu;
227

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

private PhongBan phongban;


public NhanVien(String ma, String ten, boolean gioitinh,
ChucVu chucvu,
PhongBan phongban) {
super(ma,ten);
this.gioitinh = gioitinh;
this.chucvu = chucvu;
this.phongban = phongban;
}
public NhanVien(String ma, String ten, boolean gioitinh) {
super(ma,ten);
this.gioitinh = gioitinh;
}
public NhanVien() {
super();
}
public boolean isGioitinh() {
return gioitinh;
}
public void setGioitinh(boolean gioitinh) {
this.gioitinh = gioitinh;
}
public ChucVu getChucvu() {
return chucvu;
}
public void setChucvu(ChucVu chucvu) {
this.chucvu = chucvu;
}
public PhongBan getPhongban() {
return phongban;
}
public void setPhongban(PhongBan phongban) {
this.phongban = phongban;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
}

- Coding PhongBan.java:
1
2
3
4
5
6
7
8
9
10
11

package tranduythanh.com.model;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Class lu thng tin phng ban
* @author drthanh
*
*/
public class PhongBan extends Infor implements Serializable{
228

12 private static final long serialVersionUID = 1L;


private ArrayList<NhanVien>dsnv=new ArrayList<NhanVien>();
13
public PhongBan(String ma, String ten) {
14
super(ma,ten);
15
}
16
public PhongBan() {
17
super();
18
}
19
/**
20
* Hm cho php thm mt nhn vin mi
21
* nu nhn vin c m tn ti ri th
22
* t ng tr thnh cp nht
23
* @param nv
24
*/
25
public void themNv(NhanVien nv)
26
{
27
int i=0;
28
for(;i<dsnv.size();i++)
29
{
30
NhanVien nvOld=dsnv.get(i);
31
if(nvOld.getMa().trim().equalsIgnoreCase(nv.getMa().trim()))
32
{
33
break;
34
}
35
}
36
if(i<dsnv.size())
37
dsnv.set(i, nv);
38
else
39
dsnv.add(nv);
40
}
41
public NhanVien get(int index)
42
{
43
return dsnv.get(index);
44
}
45
public int size()
46
{
47
return dsnv.size();
48
}
49
/**
50
* hm tr v trng phng ca phng ban
51
* Nu cha c trng phng th tr v null
52
* @return
53
*/
54
public NhanVien getTruongPhong()
55
{
56
for(int i=0;i<dsnv.size();i++)
57
{
58
NhanVien nv=dsnv.get(i);
59
if(nv.getChucvu()==ChucVu.TruongPhong)
60
return nv;
61
}
62
return null;
63
}
64
/**
65
* hm tr v danh sch ph trng phng
229

* v 1 phng ban c th c nhiu ph phng


66
* Nu khng c ph phng no th danh sch
67
* c kch thc =0
68
* @return
69
*/
70
public ArrayList<NhanVien>getPhoPhong()
71
{
72
ArrayList<NhanVien> dsPhoPhong=new ArrayList<NhanVien>();
73
for(NhanVien nv: dsnv)
74
{
75
if(nv.getChucvu()==ChucVu.PhoPhong)
76
dsPhoPhong.add(nv);
77
}
78
return dsPhoPhong;
79
}
80
public ArrayList<NhanVien> getListNhanVien()
81
{
82
return this.dsnv;
83
}
84
@Override
85
public String toString() {
86
// TODO Auto-generated method stub
87
String str=super.toString();
88
if(dsnv.size()==0)
89
str+="(Cha c NV)";
90
else
91
str+="(c "+dsnv.size()+" NV)";
92
return str;
93
}
94
}
95
96
- By gi ta qua package tranduythanh.com.adapter:

- 2 Adapter ny dng custom layout cho danh sch Phng ban v danh sch nhn vin.
- Ch l c 2 Adapter ny u dng chung 1 Layout tn layout_item_custom.xml:

- Bn xem source XML ca layout_item_custom.xml:


1

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


230

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/imgview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/txtShortInfor"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:id="@+id/txtDetailInfor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000080"
android:textSize="10sp"
android:textStyle="italic" />
</LinearLayout>

- By gi ta xem cch custom layout thng qua ADapter (phn customlayout Ti hng dn cc
bi tp trc, bn t xem li):
- Coding PhongBanAdapter.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

package tranduythanh.com.adapter;
import java.util.ArrayList;
import tranduythanh.com.activity.R;
import tranduythanh.com.model.NhanVien;
import tranduythanh.com.model.PhongBan;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
/**
* Class ny dng custom layout cho Danh sch phng ban
* @author drthanh
*
231

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

*/
public class PhongBanAdapter extends ArrayAdapter<PhongBan> {
Activity context;
int layoutId;
ArrayList<PhongBan> arrPhongBan;
public PhongBanAdapter(Activity context, int
textViewResourceId,
ArrayList<PhongBan> objects) {
super(context, textViewResourceId, objects);
this.context=context;
this.layoutId=textViewResourceId;
this.arrPhongBan=objects;
}
@Override
public View getView(int position, View convertView, ViewGroup
parent) {
//gn layout vo coding
convertView=context.getLayoutInflater().inflate(layoutId,
null);
//ly cc control ra theo id
TextView txtpb= (TextView)
convertView.findViewById(R.id.txtShortInfor);
TextView txtmotapb= (TextView)
convertView.findViewById(R.id.txtDetailInfor);
//Ly phng ban th position
PhongBan pb=arrPhongBan.get(position);
txtpb.setText(pb.toString());
/**
* Cc Dng lnh di ny kim tra Trng phng, ph phng
*/
String strMota="";
String tp="Trng Phng: [Cha c]";
NhanVien nv=pb.getTruongPhong();
if(nv!=null)
{
tp="Trng Phng: ["+nv.getTen()+"]";
}
ArrayList<NhanVien> dsPp=pb.getPhoPhong();
String pp="Ph phng: [Cha c]";
if(dsPp.size()>0)
{
pp="Ph phng:\n";
for(int i=0;i<dsPp.size();i++)
{
pp+=(i+1)+". "+dsPp.get(i).getTen()+"\n";
}
}
strMota=tp+"\n"+pp;
//gn thng tin cho phn chi tit
txtmotapb.setText(strMota);
return convertView;
}
}
232

- Coding NhanVienAdapter.java, phng ban Ti khng s dng ImageView, cn Nhn vin


Ti s dng ImageView :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

package tranduythanh.com.adapter;
import java.util.ArrayList;
import tranduythanh.com.activity.R;
import tranduythanh.com.model.NhanVien;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Class to customlayout cho danh sch nhn vin
* ImageVIew hin th hnh nh theo gii tnh
* @author drthanh
*
*/
public class NhanVienAdapter extends ArrayAdapter<NhanVien> {
Activity context;
int layoutId;
ArrayList<NhanVien> arrNhanVien;
public NhanVienAdapter(Activity context, int
textViewResourceId,
ArrayList<NhanVien> objects) {
super(context, textViewResourceId, objects);
this.context=context;
this.layoutId=textViewResourceId;
this.arrNhanVien=objects;
}
@Override
public View getView(int position, View convertView, ViewGroup
parent) {
//gn XML layout vo coding
convertView=context.getLayoutInflater().inflate(layoutId,
null);
//ly cc control ra
TextView txtnv= (TextView)
convertView.findViewById(R.id.txtShortInfor);
TextView txtmotanv= (TextView)
convertView.findViewById(R.id.txtDetailInfor);
ImageView img=(ImageView)
convertView.findViewById(R.id.imgview);
//ly nhn vin th position
NhanVien nv=arrNhanVien.get(position);
txtnv.setText(nv.toString());
String strMota="";
String cv="Chc v: "+nv.getChucvu().getChucVu();
String gt="Gii tnh: "+(nv.isGioitinh()?"N":"Nam");
//Kim tra gii tnh gn cho ng hnh i din
img.setImageResource(R.drawable.girlicon);
233

if(!nv.isGioitinh())
img.setImageResource(R.drawable.boyicon);
strMota=cv+"\n"+gt;
txtmotanv.setText(strMota);
return convertView;
}

52
53
54

}
- By gi ta qua package tranduythanh.com.activity:

- Ta ln lt vo tng mn hnh theo th t.


- Mn hnh chnh (MainActivity.java):
- Bn xem Outline ca mn hnh chnh chnh:

- y l XML source ca MainActivity:


1
2
3
4

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
234

5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:gravity="center"
android:text="Chng trnh qun l nhn vin"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M Phng Ban:" />
<EditText
android:id="@+id/editmapb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tn Phng Ban:" />
<EditText
235

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

android:id="@+id/editTenpb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnluupb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="Lu Phng Ban" />
</TableRow>
</TableLayout>
<TextView
android:id="@+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:text="Danh sch phng ban"
android:textColor="#FFFFFF"
android:textSize="15sp" />
<ListView
android:id="@+id/lvphongban"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

- Ta xem x l coding ca MainActivity:


1
2
3
4
5
6
7
8
9
10
11
12
13

package tranduythanh.com.activity;
import java.util.ArrayList;
import tranduythanh.com.activity.R;
import tranduythanh.com.adapter.PhongBanAdapter;
import tranduythanh.com.model.ChucVu;
import tranduythanh.com.model.NhanVien;
import tranduythanh.com.model.PhongBan;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
236

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
/**
* Class MainActivity ca ng dng
* @author drthanh
*
*/
public class MainActivity extends Activity {
//Khai bo cc Request + Result code x l Intent for
result
public static final int MO_ACTIVITY_THEM_NHAN_VIEN=1;
public static final int MO_ACTIVITY_SUA_NHAN_VIEN=2;
public static final int THEM_NHAN_VIEN_THANHCONG=3;
public static final int SUA_NHAN_VIEN_THANHCONG=4;
public static final int XEM_DS_NHAN_VIEN=5;
public static final int CAPNHAT_DS_NHAN_VIEN_THANHCONG=6;
public static final int MO_ACTIVITY_THIET_LAP_TP_PP=7;
public static final int THIET_LAP_TP_PP_THANHCONG=8;
public static final int MO_ACTIVITY_CHUYENPHONG=9;
public static final int CHUYENPHONG_THANHCONG=10;
private Button btnLuuPb;
private EditText editMapb,editTenpb;
private ListView lvpb;
private static ArrayList<PhongBan>arrPhongBan=new
ArrayList<PhongBan>();
// y dng PhongBanAdapter
private PhongBanAdapter adapterPb=null;
private PhongBan pbSelected=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFormWidgets();
addEvents();
fakeData();
}
/**
* Hm ny dng ti d liu tm ( phi nhp mi tay)
* Ti dng hm ny v d cho l
* bn c th xa n i (ni chung v thng v pht)
*/
public void fakeData()
{
NhanVien nv=null;
PhongBan pb=new PhongBan("pb1", "K thut");
237

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

nv=new NhanVien("m4", "on i Nng", true);


nv.setChucvu(ChucVu.TruongPhong);
pb.themNv(nv);
nv=new NhanVien("m5", "Trn o c", false);
nv.setChucvu(ChucVu.PhoPhong);
pb.themNv(nv);
nv=new NhanVien("m6", "Nguyn i Ti", false);
nv.setChucvu(ChucVu.PhoPhong);
pb.themNv(nv);
arrPhongBan.add(pb);
pb=new PhongBan("pb2", "Dch v");
arrPhongBan.add(pb);
pb=new PhongBan("pb3", "Truyn thng");
arrPhongBan.add(pb);
nv=new NhanVien("m1", "Nguyn Vn To", false);
nv.setChucvu(ChucVu.NhanVien);
pb.themNv(nv);
nv=new NhanVien("m2", "Nguyn Th To", true);
nv.setChucvu(ChucVu.TruongPhong);
pb.themNv(nv);
nv=new NhanVien("m3", "Nguyn Vn Teo", false);
nv.setChucvu(ChucVu.NhanVien);
pb.themNv(nv);
adapterPb.notifyDataSetChanged();
}
/**
* - Hm ny load cc control theo Id
* - Thit lp Adapter cho ListView phng ban
* - thit lp context Menu cho ListView
*/
public void getFormWidgets()
{
btnLuuPb=(Button) findViewById(R.id.btnluupb);
editMapb=(EditText) findViewById(R.id.editmapb);
editTenpb=(EditText) findViewById(R.id.editTenpb);
lvpb=(ListView) findViewById(R.id.lvphongban);
//khi to i tng phng ban adapter
//dng layout_item_custom.xml
adapterPb=new PhongBanAdapter(this,
R.layout.layout_item_custom,
arrPhongBan);
lvpb.setAdapter(adapterPb);
//ng k contextmenu cho Listview
registerForContextMenu(lvpb);
}
/**
* hm gn s kin cho cc control: button, ListView
*/
public void addEvents()
{
//Bm lu lu phng ban
btnLuuPb.setOnClickListener(new OnClickListener() {
@Override
238

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175

public void onClick(View arg0) {


// TODO Auto-generated method stub
doLuuPhongBan();
}
});
//x l lu bin tm khi nhn long - click
//phi dng ci ny bit c trc chn item no
lvpb.setOnItemLongClickListener(new OnItemLongClickListener()
{
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
//lu vt li i tng th arg2 trong danh sch
pbSelected=arrPhongBan.get(arg2);
return false;
}
});
}
/**
* hm x l lu phng ban
* n thun l a phng ban mi vo ArrayList
* ch bn phi kim tra trng lp Id, hay cc
* thng tin y cha y
* gi adapterPb.notifyDataSetChanged(); cp nht ListView
*/
public void doLuuPhongBan()
{
String mapb=editMapb.getText()+"";
String tenpb=editTenpb.getText()+"";
PhongBan pb=new PhongBan(mapb, tenpb);
arrPhongBan.add(pb);
adapterPb.notifyDataSetChanged();
}
/**
* hm ny gn COntextMenu vo ng dng
* hc t lu ri, phi t hiu
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.contextmenu_phongban, menu);
}
/**
* hm ny x l ngi s dng va chn menuitem no
* ta da vo Id x l
*/
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.mnuthemnv:
doThemNhanVien();
239

176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229

break;
case R.id.mnudanhsachnv:
doDanhSachNhanVien();
break;
case R.id.mnutruongphong:
doThietLapLanhDao();
break;
case R.id.mnuxoapb:
doXoaPhongBan();
break;
}
return super.onContextItemSelected(item);
}
/**
* khi chn menu Thm nhn vin, n thun ch l hin th
* mn hn thm nhn vin (vi dng Dialog)
* nh l dng startActivityForResult
* do ta lng nghe kt qu ti hm onActivityResult
*/
public void doThemNhanVien()
{
Intent i=new Intent(this, ThemNhanVienActivity.class);
startActivityForResult(i, MO_ACTIVITY_THEM_NHAN_VIEN);
}
/**
* hm onActivityResult x l kt qu tr v
* sau khi gi startActivityForResult kt thc
*/
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//mn hnh thm mi nhn vin tr kt qu v
if(resultCode==THEM_NHAN_VIEN_THANHCONG)
{
//Cch ly d liu hc ri, ko ni li
Bundle bundle= data.getBundleExtra("DATA");
NhanVien nv= (NhanVien) bundle.getSerializable("NHANVIEN");
pbSelected.themNv(nv);
adapterPb.notifyDataSetChanged();
}
//Mn hnh thit lp lnh o/ cp nht danh sch tr
//kt qu v
else if(resultCode==THIET_LAP_TP_PP_THANHCONG||
resultCode==CAPNHAT_DS_NHAN_VIEN_THANHCONG)
{
//Cch ly d liu hc ri, ko ni li
Bundle bundle= data.getBundleExtra("DATA");
PhongBan pb= (PhongBan) bundle.getSerializable("PHONGBAN");
//n thun l xa danh sch c
pbSelected.getListNhanVien().clear();
//ri cp nht li ton b danh sch mi
//sinh vin c th chn gii php thng minh hn
//tc l phn t no b nh hng th x l phn t
240

230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283

pbSelected.getListNhanVien().addAll(pb.getListNhanVien());
adapterPb.notifyDataSetChanged();
}
}
/**
* hm cho php danh xem danh sch nhn vin ca phng
* ban ang chn, n thun l m DanhSachNhanVienActivity
* v truyn phng ban qua -->ton b danh sch nhn vin
* s c hin th trong DanhSachNhanVienActivity
*/
public void doDanhSachNhanVien()
{
Intent i=new Intent(this, DanhSachNhanVienActivity.class);
Bundle bundle=new Bundle();
bundle.putSerializable("PHONGBAN", pbSelected);
i.putExtra("DATA", bundle);
startActivityForResult(i, XEM_DS_NHAN_VIEN);
}
/**
* hm cho php m mn hnh thit lp lnh o phng ban
* Trng phng v ph phng
* ThietLapTruongPhongActivity s c 2 ListView
* - Listview 1 hin th dang radiobutton ch chn 1 trng
phng
* - ListView 2 hin th dng Checkbox cho php chn nhiu ph
phng
*/
public void doThietLapLanhDao()
{
Intent i=new Intent(this, ThietLapTruongPhongActivity.class);
Bundle bundle=new Bundle();
bundle.putSerializable("PHONGBAN", pbSelected);
i.putExtra("DATA", bundle);
startActivityForResult(i, MO_ACTIVITY_THIET_LAP_TP_PP);
}
/**
* hm cho php xa phng ban ang chn
*/
public void doXoaPhongBan()
{
AlertDialog.Builder builder=new AlertDialog.Builder (this);
builder.setTitle("Hi xa");
builder.setMessage("Bn c chc chn mun xa
["+pbSelected.getTen()+"]");
builder.setIcon(android.R.drawable.ic_input_delete);
builder.setNegativeButton("Khng", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
arg0.cancel();
}
});
builder.setPositiveButton("", new
241

284
285
286
287
288
289
290
291
292
293
294
295
296

DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
arrPhongBan.remove(pbSelected);
adapterPb.notifyDataSetChanged();
}
});
builder.show();
}
/**
* Ti c tnh cung cp hm ny cc Activity khc u
* c th truy sut c danh sch phng ban tng th
* @return
*/
public static ArrayList<PhongBan> getListPhongBan()
{
return arrPhongBan;
}
}

- Ta qua mn hnh thm nhn vin. Ch l mn hnh ny bn phi cu hnh m dng Dialog.
- xem layout:

- Bn xem XML source code ca mn hnh ny:


242

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ThemNhanVienActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:text="Thng Tin Nhn Vin"
android:textColor="#FFFFFF"
android:textSize="15sp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M NV:" />
<EditText
android:id="@+id/editMaNV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
243

55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

android:text="Tn NV:" />


<EditText
android:id="@+id/editTenNV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gii Tnh:" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/radNam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Nam" />
<RadioButton
android:id="@+id/radNu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="N" />
</RadioGroup>
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnxoatrang"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Xa trng" />
<Button
244

109
110
111
112
113
114
115
116
117
118

android:id="@+id/btnluunv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lu nhn vin" />
</TableRow>
</TableLayout>
</LinearLayout>

- Gi ta xem x l coding cho phn thm nhn vin (ThemNhanVienActivity):


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

package tranduythanh.com.activity;
import tranduythanh.com.activity.R;
import tranduythanh.com.model.ChucVu;
import tranduythanh.com.model.NhanVien;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
/**
* class ny cho php thm mi mt nhn vin vo
* Phng ban ang chn
* @author drthanh
*
*/
public class ThemNhanVienActivity extends Activity {
private Button btnXoaTrang,btnLuuNhanVien;
private EditText editManv,editTenNv;
private RadioButton radNam;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_them_nhan_vien);
getFormWidgets();
addEvents();
}
/**
* hm ly cc control theo id
*/
public void getFormWidgets()
{
btnXoaTrang=(Button) findViewById(R.id.btnxoatrang);
btnLuuNhanVien=(Button) findViewById(R.id.btnluunv);
editManv=(EditText) findViewById(R.id.editMaNV);
editTenNv=(EditText) findViewById(R.id.editTenNV);
245

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95

radNam=(RadioButton) findViewById(R.id.radNam);
}
/**
* hm gn s kin
*/
public void addEvents()
{
btnXoaTrang.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
doXoaTrang();
}
});
btnLuuNhanVien.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
doLuuNhanVien();
}
});
}
/**
* n thun l xa trng d liu ca cc control
* ri focus ti m
*/
public void doXoaTrang()
{
editManv.setText("");
editTenNv.setText("");
editManv.requestFocus();
}
/**
* hm lu nhn vin theo phng ban
* truyn nhn vin qua MainActivity
* MainActivity c nhim v ly c nhn vin ny
* v a h vo phng ban chn lc ny
*/
public void doLuuNhanVien()
{
NhanVien nv=new NhanVien();
nv.setMa(editManv.getText()+"");
nv.setTen(editTenNv.getText()+"");
nv.setChucvu(ChucVu.NhanVien);
nv.setGioitinh(!radNam.isChecked());
Intent i=getIntent();
Bundle bundle=new Bundle();
bundle.putSerializable("NHANVIEN", nv);
i.putExtra("DATA", bundle);
setResult(MainActivity.THEM_NHAN_VIEN_THANHCONG, i);
finish();
}
}
246

96
- Tip tc ta xem mn hnh Xem danh sch nhn vin:
- bn xem outline:

- Xem XML Resource ca activity_danh_sach_nhan_vien.xml:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".DanhSachNhanVienActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageButton
android:id="@+id/btnback"
android:layout_width="16dp"
android:layout_height="16dp"
android:contentDescription="TODO"
android:src="@drawable/back" />
<TextView
android:id="@+id/txtmsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:textColor="#FFFFFF" />
247

26
27
28
29
30
31
32
33
34
35

</LinearLayout>
<ListView
android:id="@+id/lvnhanvien"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

- Xem coding x l phn xem danh sch nhn vin (DanhSachNhanVienActivity) :


- Class ny rt phc tp, n cn cha Context menu cho php:
+ Sa nhn vin
+ Chuyn phng ban cho nhn vin
+ Xa nhn vin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

package tranduythanh.com.activity;
import java.util.ArrayList;
import tranduythanh.com.activity.R;
import tranduythanh.com.adapter.NhanVienAdapter;
import tranduythanh.com.model.NhanVien;
import tranduythanh.com.model.PhongBan;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
/**
* class ny dng hin th danh sch nhn vin
* Class ny cng phc tp khng km MainActivity
* nh l dng custom layout
* - Hin th danh sch
* - cho php chnh sa
* - cho php chuyn phng ban
* - cho php xa nhn vin
* @author drthanh
248

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

*
*/
public class DanhSachNhanVienActivity extends Activity {
TextView txtmsg;
ImageButton btnback;
ListView lvNhanvien;
ArrayList<NhanVien> arrNhanvien=null;
//Nhn vin Adapter hin th thng tin
//v chi tit : chc v, gii tnh
NhanVienAdapter adapter=null;
PhongBan pb=null;
private NhanVien nvSelected=null;
private int position=-1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_danh_sach_nhan_vien);
txtmsg=(TextView) findViewById(R.id.txtmsg);
btnback=(ImageButton) findViewById(R.id.btnback);
lvNhanvien=(ListView) findViewById(R.id.lvnhanvien);
getDataFromMain();
addEvents();
registerForContextMenu(lvNhanvien);
}
/**
* hm ly gi tr t MainActivity
* s truyn phng ban qua
* bn ny ly phng ban v da vo phng ban ny
* ly ra danh sch nhn vin
*/
public void getDataFromMain()
{
Intent i=getIntent();
Bundle b=i.getBundleExtra("DATA");
pb= (PhongBan) b.getSerializable("PHONGBAN");
arrNhanvien=pb.getListNhanVien();
adapter=new NhanVienAdapter(this,
R.layout.layout_item_custom,
arrNhanvien);
lvNhanvien.setAdapter(adapter);
txtmsg.setText("DS nhn vin ["+pb.getTen()+"]");
}
/**
* hm gn s kin ( qu quen thuc ri)
* c lu vt li nhn vin va chn x l
* cho contextmenu
*/
public void addEvents()
{
btnback.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
doUpdateToMain();
249

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140

}
});
lvNhanvien.setOnItemLongClickListener(new
OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View
arg1,
int arg2, long arg3) {
nvSelected=arrNhanvien.get(arg2);
position=arg2;
return false;
}
});
}
/**
* hm gn context menu( qu quen thuc)
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.contextmenu_nhanvien,
menu);
}
/**
* hm x l s kin chn menuitem ( quen thuc qu)
*/
@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId())
{
case R.id.mnusuanv:
doSuaNhanVien();
break;
case R.id.mnuchuyenpb:
doChuyenPhongBan();
break;
case R.id.mnuxoanv:
doXoaNhanVien();
break;
}
return super.onContextItemSelected(item);
}
/**
* hm onActivityResult x l kt qu tr v
* cho trng hp x dng COntext Menu m cc
* Activity khc
*/
@Override
protected void onActivityResult(int requestCode, int
resultCode, Intent data) {
250

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194

// TODO Auto-generated method stub


super.onActivityResult(requestCode, resultCode, data);
//ly kt qu sa nhn vin thnh cng
if(resultCode==MainActivity.SUA_NHAN_VIEN_THANHCONG)
{
Bundle b=data.getBundleExtra("DATA");
NhanVien nv= (NhanVien) b.getSerializable("NHANVIEN");
arrNhanvien.set(position, nv);
adapter.notifyDataSetChanged();
}
//ly kt qu chuyn phng ban thnh cng
else if(resultCode==MainActivity.CHUYENPHONG_THANHCONG)
{
arrNhanvien.remove(nvSelected);
adapter.notifyDataSetChanged();
}
}
/**
* hm sa nhn vin
* n gin l m Activity sa nhn vin ln
* ri truyn nhn vin ang chn qua Activity
*
*/
public void doSuaNhanVien()
{
Intent i=new Intent(this, SuaNhanVienActivity.class);
Bundle b=new Bundle();
b.putSerializable("NHANVIEN", nvSelected);
i.putExtra("DATA", b);
startActivityForResult(i,
MainActivity.MO_ACTIVITY_SUA_NHAN_VIEN);
}
/**
* hm chuyn phng ban cho nhn vin ang chn
* n thun l m Activity chuyn phng ban
* Activity ny c nhim v hin th ton b phng ban
* ri cho php ngi s dng chn phng ban chuyn
*/
public void doChuyenPhongBan()
{
Intent i=new Intent(this, ChuyenPhongBanActivity.class);
Bundle b=new Bundle();
b.putSerializable("NHANVIEN", nvSelected);
i.putExtra("DATA", b);
startActivityForResult(i,
MainActivity.MO_ACTIVITY_CHUYENPHONG);
}
/**
* hm cho php xa nhn vin hin ti
* ( quen thuc qu)
*/
public void doXoaNhanVien()
{
AlertDialog.Builder builder=new AlertDialog.Builder (this);
builder.setTitle("Hi xa");
251

195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227

builder.setMessage("Bn c chc chn mun xa


["+nvSelected.getTen()+"]");
builder.setIcon(android.R.drawable.ic_input_delete);
builder.setNegativeButton("Khng", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
arg0.cancel();
}
});
builder.setPositiveButton("", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
arrNhanvien.remove(nvSelected);
adapter.notifyDataSetChanged();
}
});
builder.show();
}
/**
* khi nhn nt Back (hnh back)
* th truyn thng s v MainActivity cp nht
* phng ban
*/
public void doUpdateToMain()
{
Intent i=getIntent();
Bundle b=new Bundle();
b.putSerializable("PHONGBAN", pb);
i.putExtra("DATA", b);
setResult(MainActivity.CAPNHAT_DS_NHAN_VIEN_THANHCONG, i);
finish();
}
}

- Ta tip tc lm vic vi mn hnh sa nhn vin, v mn hnh ny s dng chung Layout vi mn


hnh thm nhn vin. Nn Ti ch m t phn x l coding m thi (SuaNhanVienActivity):
1
2
3
4
5
6
7
8
9
10
11

package tranduythanh.com.activity;
import tranduythanh.com.model.NhanVien;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
252

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

/**
* class ny cho php sa nhn vin c chn trong
Danhsachnhanvien
* s dng chung Layout vi Thm nhn vin
* Khng cho sa m s nhn vin
* khi bm lu th cp nht li (rt n gin)
* @author drthanh
*
*/
public class SuaNhanVienActivity extends Activity{
EditText editMa,editTen;
RadioButton radNam;
Button btnClear,btnSave;
NhanVien nv=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_them_nhan_vien);
getFormWidgets();
getDefaultData();
addEvents();
}
/**
* hm ly cc control theo id
*/
public void getFormWidgets()
{
editMa=(EditText) findViewById(R.id.editMaNV);
editTen=(EditText) findViewById(R.id.editTenNV);
radNam=(RadioButton) findViewById(R.id.radNam);
editMa.setEnabled(false);
editTen.requestFocus();
btnClear=(Button) findViewById(R.id.btnxoatrang);
btnSave=(Button) findViewById(R.id.btnluunv);
}
/**
* hm ly gi tr t DanhSachNhanVienActivity truyn qua
* hin th
*/
public void getDefaultData()
{
Intent i =getIntent();
Bundle b=i.getBundleExtra("DATA");
nv=(NhanVien) b.getSerializable("NHANVIEN");
editMa.setText(nv.getMa());
editTen.setText(nv.getTen());
radNam.setChecked(true);
if(nv.isGioitinh())
radNam.setChecked(false);
}
public void addEvents()
{
btnClear.setOnClickListener(new OnClickListener() {
253

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
editTen.setText("");
editTen.requestFocus();
}
});
/**
* bm lu th ng ca s sa ny
* v truyn d liu qua mn hnh cha n t cp nht
*/
btnSave.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i =getIntent();
nv.setTen(editTen.getText()+"");
nv.setGioitinh(!radNam.isChecked());
Bundle b=new Bundle();
b.putSerializable("NHANVIEN", nv);
i.putExtra("DATA", b);
setResult(MainActivity.SUA_NHAN_VIEN_THANHCONG, i);
finish();
}
});
}
}

- Ta qua mn hnh chuyn phng ban cho nhn vin:


- Bn xem layout XML:

- Mn hnh ny l mn hnh con ca mn hnh Xem danh sch nhn nhin (lc dng Context Menu).
254

- Khi chn nhn vin no th s tin hnh m mn hnh chuyn phng ban cho nhn vin .
- xem XML Resource:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ChuyenPhongBanActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:text="Chn phng ban chuyn"
android:textColor="#FFFFFF"
android:textSize="15sp" />
<ListView
android:id="@+id/lvphongban"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="3" >
</ListView>
<ImageButton
android:id="@+id/imgapply"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_gravity="center"
android:contentDescription="Thit lp"
android:src="@drawable/apply" />
</LinearLayout>

- Bn xem x l coding cho phn chuyn phng ban:


1
2
3
4
5
6
7
8
9
10
11
12
13

package tranduythanh.com.activity;
import java.util.ArrayList;
import tranduythanh.com.model.NhanVien;
import tranduythanh.com.model.PhongBan;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
255

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageButton;
import android.widget.ListView;
/**
* Class dng x l chuyn phng ban cho nhn vin
* @author drthanh
*
*/
public class ChuyenPhongBanActivity extends Activity {
ListView lvPb;
private static ArrayList<PhongBan>arrPhongBan=null;
ArrayAdapter<PhongBan>adapter;
ImageButton btnApply;
NhanVien nv=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chuyen_phong_ban);
getFormWidgets();
//ly nhn vin t mn hnh xem danh sch nhn vin
Intent i=getIntent();
Bundle b= i.getBundleExtra("DATA");
nv=(NhanVien) b.getSerializable("NHANVIEN");
}
/**
* hm ly control theo id
* ng thi load ton b danh sch phng ban MainActivity
* ln ListView s dng
* android.R.layout.simple_list_item_single_choice ->dng Radio
* Bt buc phi x l hm: lvPb.setOnItemClickListener
* gn checked cho Radio
*/
public void getFormWidgets()
{
lvPb=(ListView) findViewById(R.id.lvphongban);
btnApply=(ImageButton) findViewById(R.id.imgapply);
arrPhongBan=MainActivity.getListPhongBan();
adapter=new ArrayAdapter<PhongBan>
(this, android.R.layout.simple_list_item_single_choice,
arrPhongBan);
lvPb.setAdapter(adapter);
lvPb.setOnItemClickListener(new OnItemClickListener() {
boolean somethingChecked = false;
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int
arg2,
long arg3) {
//hin nhin View arg1 l CheckedTextView
if(somethingChecked){
CheckedTextView cv = (CheckedTextView) arg1;
256

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

cv.setChecked(false);
}
CheckedTextView cv = (CheckedTextView) arg1;
if(!cv.isChecked())
{
cv.setChecked(true);
arrPhongBan.get(arg2).themNv(nv);
}
somethingChecked=true;
}
});
//khi chn nt Apply th tin hnh ng mn hnh ny
//v truyn lnh v cho DanhSachNhanVienACtivity
btnApply.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
doApply();
}
});
}
public void doApply()
{
setResult(MainActivity.CHUYENPHONG_THANHCONG);
finish();
}
}

- Ta qua mn hnh cui cng: Thit lp trng ph phng cho nhn vin
- Mn hnh ny l mn hnh con ca MainActivity.
- Khi chn phng ban no th thit lp trng ph phng cho phng ban .
- xem Layout (activity_thiet_lap_truong_phong.xml):

257

- Xem XML resource:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

</pre>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ThietLapTruongPhongActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:text="Chn trng phng"
android:textColor="#FFFFFF"
android:textSize="15sp" />
<ListView
android:id="@+id/lvtruongphong"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="3" >
</ListView>
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000"
android:text="Chn ph phng"
258

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

android:textColor="#FFFFFF"
android:textSize="15sp" />
<ListView
android:id="@+id/lvphophong"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2" >
</ListView>
<ImageButton
android:id="@+id/imgapply"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_gravity="center"
android:contentDescription="Thit lp"
android:src="@drawable/apply" />
</LinearLayout>
<pre>

- xem x l coding:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

package tranduythanh.com.activity;
import java.util.ArrayList;
import tranduythanh.com.activity.R;
import tranduythanh.com.model.ChucVu;
import tranduythanh.com.model.NhanVien;
import tranduythanh.com.model.PhongBan;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.app.Activity;
import android.content.Intent;
/**
* mn hnh s hin th danh sch nhn vin vo 2 ListView
khc nhau
* ListView 1 dng Radio chn trng phng
* ListView 2 dng Checkbox chn ph phng
* @author drthanh
*
*/
public class ThietLapTruongPhongActivity extends Activity {
ListView lvtruongphong,lvphophong;
ArrayList<NhanVien>arrNvForTP=new ArrayList<NhanVien>();
259

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

ArrayAdapter<NhanVien> adapterForTP;
ArrayList<NhanVien>arrNvForPP=new ArrayList<NhanVien>();
ArrayAdapter<NhanVien> adapterForPP;
ImageButton btnApply;
int lastChecked=-1;
PhongBan pb=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thiet_lap_truong_phong);
getFormWidgets();
}
/**
* hm ly control theo id
* x l s kin checked (chn chc v cho nhn vin)
* Mi th l hng i tng nn n t tham chiu
*/
public void getFormWidgets()
{
lvtruongphong=(ListView) findViewById(R.id.lvtruongphong);
lvtruongphong.setTextFilterEnabled(true);
lvtruongphong.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lvtruongphong.setOnItemClickListener(new
OnItemClickListener() {
boolean somethingChecked = false;
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int
arg2,
long arg3) {
arrNvForTP.get(arg2).setChucvu(ChucVu.TruongPhong);
if(somethingChecked){
CheckedTextView cv = (CheckedTextView) arg1;
cv.setChecked(false);
}
CheckedTextView cv = (CheckedTextView) arg1;
if(!cv.isChecked())
{
cv.setChecked(true);
arrNvForTP.get(arg2).setChucvu(ChucVu.TruongPhong);
}
else
{
arrNvForTP.get(arg2).setChucvu(ChucVu.NhanVien);
}
lastChecked = arg2;
somethingChecked=true;
}
});
lvphophong=(ListView) findViewById(R.id.lvphophong);
lvphophong.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int
arg2,
260

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139

long arg3) {
CheckedTextView cv = (CheckedTextView) arg1;
if(!cv.isChecked())
{cv.setChecked(true);
arrNvForPP.get(arg2).setChucvu(ChucVu.PhoPhong);
}
else
{cv.setChecked(false);
arrNvForPP.get(arg2).setChucvu(ChucVu.NhanVien);
}
}
});
adapterForTP=new ArrayAdapter<NhanVien>(this,
android.R.layout.simple_list_item_single_choice,
arrNvForTP);
adapterForPP=new ArrayAdapter<NhanVien>(this,
android.R.layout.simple_list_item_multiple_choice,
arrNvForPP);
lvtruongphong.setAdapter(adapterForTP);
lvphophong.setAdapter(adapterForPP);
//Ly c phng ban gi qua t MainActivity
Intent i= getIntent();
Bundle bundle= i.getBundleExtra("DATA");
pb= (PhongBan) bundle.getSerializable("PHONGBAN");
addNvToListTP(pb);
addNvToListPP(pb);
adapterForTP.notifyDataSetChanged();
adapterForPP.notifyDataSetChanged();
btnApply=(ImageButton) findViewById(R.id.imgapply);
btnApply.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
doApply();
}
});
}
/**
* gi thng tin li Mainactivity sau khi thit lp
*/
public void doApply()
{
Intent i=getIntent();
Bundle bundle=new Bundle();
bundle.putSerializable("PHONGBAN", pb);
i.putExtra("DATA", bundle);
setResult(MainActivity.THIET_LAP_TP_PP_THANHCONG, i);
finish();
}
/**
* duyt ton b nhn vin vo danh sch ng vin Trng phng
261

* @param pb
*/
public void addNvToListTP(PhongBan pb)
{
arrNvForTP.clear();
for(NhanVien nv:pb.getListNhanVien())
{
arrNvForTP.add(nv);
}
}
/**
* duyt ton b nhn vin vo danh sch ng vin ph phng
* @param pb
*/
public void addNvToListPP(PhongBan pb)
{
arrNvForPP.clear();
for(NhanVien nv:pb.getListNhanVien())
{
arrNvForPP.add(nv);
}
}

140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
}

- Nh vy Ti trnh by xong v d 25.


- Bi tp ny n rt kh v phc tp, bn phi c i c li v lm i lm li
- Nu nh bi tp ny bn hiu th coi nh bn hiu c phn ln Intent v bit cch ng dng
n.
- Bn ti coding mu ton b ti y:http://www.mediafire.com/?x8yyy2rewwcf9su
- Bi tp sau Ti s c thm 1 v d v implicit intent (cng l intent). Mc ch ca v d ny l Ti
vit chng trnh gi in thoi v nhn tin sms (khng s dng chng trnh c sn ca Android).

262

Bi tp 26: Dng Implicit Intent vit chng


trnh gi in thoi v nhn tin SMS
- bi tp 24 v bi tp 25 Ti hng dn rt k v cch s dng Intent (cc intent ny cn gi
lExplicit Intent).
- Trong bi tp 26 Ti s hng dn bn cch s dng Implicit Intent (bn c hiu nm na l nhng
Intent c xy dng sn, c cung cp sn trong h iu hnh Android). Tm thi bn c hiu nh
vy i, nu nh Ti sai th Ti s sa li sau, v c th c nhiu cch hiu khc hay hn Ti nhiu.
- Ti t vn nh sau:
+ Mt ngy p tri khng khip no chng hn 3h gi ngy 13 thng 3 nm 2013, D ng
ght ca bn b rt xung nn nh ci bch bch bch. b m, mo my ming v h lun chng
trnh gi in thoi v nhn tin SMS (b h 2 chc nng ny, nhng m D M vn hot ng).
Khng ai thm sa D cho bn, xui ci bn ang hc Android lp ca Ti, Ti yu cu bn phi t
lp trnh ra chc nng Gi in thoi v nhn tin SMS cho D (d nhin thit b ca bn s dng
Android OS). Vy bn phi lm ri, v khng lm s b 0 im.
+ Vy dng nhng k thut no c th vit c chc nng nghe gi+ nhn tin SMS thay th cho
chng trnh c sn ca Android?
+ Ti s hng dn cc bn vo bui sau, bn hy ch theo di. Trong thi gian ch i th Ti
khuyn cc bn phi lm i lm li bi tp 24 v bi tp 25.
- Ti gii hn bi tp ny nh sau: Bi tp ny n thun ch l cho php nhp tn v s in thoi
vo b nh (khng phi danh b in thoi) sau hin th danh sch ny vo ListView, ListView s
cung cp ContextMenu c 2 mc: Gi in thoi v Nhn tin. Qua phn Content Provider v
Telephony API cc bn s c hc k hn v cch ly danh b t in thoi ra, cch c tin nhn
trong inbox ra, cch tng tc vi danh b v tin nhn Nn bi tp ny cc bn xem n nh l
Chi chi vui thi.
- Mu cht ca bi ny l cc bn phi t bit cch to mt cuc gi, cch gi tin nhn trong Android
nh th no, my phn ru ria khc cc bn ng bn tm.
- c th gi in thoi v nhn tin th cc bn phi khai bo trong Manifest cc permission sau:
<uses-permission android:name=android.permission.CALL_PHONE />
<uses-permission android:name=android.permission.SEND_SMS />
- Bn xem giao din ca chng trnh:

263

- Nhn Save Contact lu thng tin vo ListView nh hnh.


- X l context menu cho ListView:

- Chc nng Call to gi, mn hnh gi s hin ra nh bn di:

264

- Chc nng Send Sms to , cho ra mn hnh gi tin nhn nh bn di:

- Nhn Send Message gi. y Ti mun ni cc bn rng c 2 hnh vi gi tin nhn.


1) gi tin nhn m khng bit kt qu thnh cng hay khng (d dng, nhng m khng nn.
Trng hp ny thng xuyn sy ra. Ti ly c th trng hp ca Ti, nh Ti trn Ni
sng thng yu v khng lin lc c, nu vit theo cch ny th Bn s khng bit l gi cho
Ti thnh cng hay khng.)
V d: Vit nh bn di th c th gi c tin nhn trng hp bnh thng, khng kim tra kt
qu tr v (Cn kim tra kt qu tr v bn xem trong coding y ).
final SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage( 0987773061, null, Hello teo teo!, null, null);
2) gi tin nhn c kim tra kt qu thnh cng (ta nn dng cch ny, nhng m kh v cc bn
cha hc IntentFilter, nhng Ti vn a vo, c g cc bn tm hiu sau)
- By gi bn xem cu to chng trnh:

265

- Giao din chnh activity_main.xml:

- Xem source XML activity_main.xml:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2"
android:background="#008000"
android:gravity="center"
android:text="&quot;Chi Chi&quot; Phone Utility"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</TableRow>
266

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name:" />
<EditText
android:id="@+id/editName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone:" />
<EditText
android:id="@+id/editPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="phone" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnSaveContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="Save Contact" />
</TableRow>
</TableLayout>
<TextView
267

86
87
88
89
90
91
92
93
94
95
96
97

android:id="@+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#008000" />
<ListView
android:id="@+id/lvContact"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

- Cc XML resource khc cc bn t xem trong project.


- Class MyContact:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

package tranduythanh.com;
import java.io.Serializable;
public class MyContact implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public MyContact(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public MyContact() {
super();
}
@Override
public String toString() {
return this.name+"["+this.phone+"]";
}
}
268

- Class x l MainActivity:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

package tranduythanh.com;
import java.util.ArrayList;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
EditText editName,editPhone;
Button btnSave;
ListView lvContact;
//Danh sch contact a vo ListView
ArrayList<MyContact>arrContact=new ArrayList<MyContact>();
ArrayAdapter<MyContact>adapter=null;
MyContact selectedContact=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doGetFormWidgets();
doAddEvents();
}
public void doGetFormWidgets()
{
btnSave=(Button) findViewById(R.id.btnSaveContact);
editName=(EditText) findViewById(R.id.editName);
editPhone=(EditText) findViewById(R.id.editPhone);
lvContact=(ListView) findViewById(R.id.lvContact);
//to i tng adapter
adapter=new ArrayAdapter<MyContact>
(this, android.R.layout.simple_list_item_1,arrContact);
//gn Adapter vo cho ListView
lvContact.setAdapter(adapter);
//thit lp contextmenu cho ListView
registerForContextMenu(lvContact);
}
public void doAddEvents()
{
btnSave.setOnClickListener(new OnClickListener() {
269

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
doSaveContact();
}
});
//ly contact c chn trc trong ListView
//V khi m context menu s lm mt focus nn ta phi lu
li trc
//khi m context menu
lvContact.setOnItemLongClickListener(new
OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View
arg1,
int arg2, long arg3) {
//lu vt contact c chn trong ListView
selectedContact=arrContact.get(arg2);
return false;
}
});
}
/**
* mi ln nhn Save contact th gi hm ny
* cp nht contact vo List view
* bn lu l ta ch lm trong b nh
* khng phi lu vo Danh B (phn ny hc sau)
*/
public void doSaveContact()
{
MyContact ct=new MyContact();
ct.setName(editName.getText()+"");
ct.setPhone(editPhone.getText()+"");
arrContact.add(ct);
adapter.notifyDataSetChanged();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
//gn context menu vo
getMenuInflater().inflate(R.menu.phonecontextmenu, menu);
menu.setHeaderTitle("Call- Sms");
menu.getItem(0).setTitle("Call to
"+selectedContact.getPhone());
menu.getItem(1).setTitle("Send sms to
"+selectedContact.getPhone());
}
@Override
public boolean onContextItemSelected(MenuItem item) {
//kim tra xem Menu Item no c chn
switch(item.getItemId())
270

{
case R.id.mnuCall:
doMakeCall();
break;
case R.id.mnuSms:
doMakeSms();
break;
case R.id.mnuRemove:
arrContact.remove(selectedContact);
adapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
/**
* Thc hin gi in thoi
*/
public void doMakeCall()
{
Uri uri=Uri.parse("tel:"+selectedContact.getPhone());
Intent i=new Intent(Intent.ACTION_CALL, uri);
startActivity(i);
}
/**
* thc hin m giao din gi tin nhn
* Truyn thng tin contact ang chn qua
* activity mi
*/
public void doMakeSms()
{
Intent i=new Intent(this, MySMSActivity.class);
Bundle b=new Bundle();
b.putSerializable("CONTACT", selectedContact);
i.putExtra("DATA", b);
startActivity(i);
}

107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
}

-Bn xem dng lnh 96 thit lp tiu cho context menu


- Dng lnh 97,98 sa li title cho cc menuitem ng vi mi contact.
- Dng lnh 121 c hm doMakeCall gi in thoi cho s no . Bn nhn vo ni dung bn
trong xem quy tc to lnh gi.
- Class x l gi tin nhn MySMSActivity:
1
2
3
4
5
6

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
271

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MySMSActivity extends Activity {
Button btnSendSMS;
EditText editContent;
TextView txtSendTo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_sms);
btnSendSMS =(Button) findViewById(R.id.btnSendSms);
editContent =(EditText) findViewById(R.id.editSMS);
txtSendTo=(TextView) findViewById(R.id.txtSendTo);
//Ly thng tin t Intent
Intent i =getIntent();
Bundle b=i.getBundleExtra("DATA");
final MyContact c=(MyContact) b.getSerializable("CONTACT");
btnSendSMS.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
sendSms(c);
}
});
txtSendTo.setText("Send to : "+c.getPhone());
}
/**
* hm dng gi tin nhn c kim tra kt qu tr v
* Ti cha gii thch y c v n lin quan rt nhiu
* kin thc, khi no ti Broadcast Receiver, telephony Ti s
* gii thch li
* @param c
*/
public void sendSms(MyContact c)
{
//ly mc nh SmsManager
final SmsManager sms = SmsManager.getDefault();
Intent msgSent = new Intent("ACTION_MSG_SENT");
//Khai bo pendingintent kim tra kt qu
final PendingIntent pendingMsgSent =
PendingIntent.getBroadcast(this, 0, msgSent, 0);
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
int result = getResultCode();
272

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

String msg="Send OK";


if (result != Activity.RESULT_OK) {
msg="Send failed";
}
Toast.makeText(MySMSActivity.this, msg,
Toast.LENGTH_LONG).show();
}
}, new IntentFilter("ACTION_MSG_SENT"));
//Gi hm gi tin nhn i
sms.sendTextMessage(c.getPhone(), null,
editContent.getText()+"",
pendingMsgSent, null);
finish();
}
}

- Dng lnh 51 c hm sendSms gi tin nhn i. hm ny Ti vit c kim tra kt qu gi thnh


cng hay khng. Ti khng gii thch nhiu v n lin quan ti qu nhiu kin thc. Tm thi bn c
gng hiu tng dng lnh Ti gii thch bn trong l ok ri.
- Bn c th ti coding mu y y:http://www.mediafire.com/?ilpeqrycsbdswzg
- Bi ny l tin lm cc ng dng khc lin quan ti Telephony.
- n y coi nh bn tm n v Intent. Bi tp k tip Ti s hng dn cc bn lm v a ngn
ng trong Android, ni ti Mobile th thng n phi h tr a ngn ng (c th gii u si, vi
nhng ngn ng khc nhau).

273

Bi tp 27: a ngn ng trong Android


- Bi tp ny Ti s hng dn cc bn cch to a ngn ng trong Android.
- Mobile tr thnh thit b khng th thiu c trn th gii ny. Ngi lm rung, bn v s, bn
bnh m, nhn vin vn phng, gim c, nhn vin bn hng, bn tm lum every body. u s
hu 1 ch D.
- H tr a ngn ng gip phn mm ta bn chy, mc tiu vit phn mm ra bn kim tin ch
khng phi vit ra t k 1 mnh. Nn cc bn phi bit lm a ngn ng.

- Bi tp ny Ti s lm 3 ngn ng: Ting Anh, Ting Php, Ting Vit.


- Ting Php Ti khng bit g c (1 ch cn i khng bit, nh ch Khng b i (dc hoc
ngang) ra c bng ting Php th Ti khng bit c), Ti dch trn google.
- a ngn ng ch l lm trn XML resource l chnh (coding khng phi sa i, ch sa resource
theo ng ngn ng). Khi ta lm ng ngn ng theo resource th khi ngi s dng chuyn ngn
ng trong Android n s t ti ng resource ngn ng m ta to.
- Cu hnh ngn ng trong Android (bn t m), Ti chp mn hnh bn trong chn ngn ng:

- Ti c v d v 4 ma trong nm: xun, h , thu ,ng:


274

- Khi Setting trong Android l ting Anh:

- Ting Php:

- Ting vit:

- Bn ch l cc hnh trn Ti hon ton khng sa i coding, Ti ch i ngn ng trong


Android, n t ng ti ng Resource XML ngn ng.
275

- Cch to Resource XML ngn ng:


- Cn ch : tt c cc string resource id cc ngn ng khc nhau u phi c cng id.
- Mi mt Quc gia s c mt Code ring vi 2 k t:

-Bm chut phi vo Android Project/ chn Android XML resource:


- Mn hnh trn hin th ra. Bn chn vo mc Language ri click biu tng s 1.
- Language s hin th vo danh sch gia
- mc s 2 bn chn Code Quc gia (theo ngn ng)
- Mc Folder s 3 s c ni km ng sau values.
- Bn xem cu trc th mc ca Android Project sau khi bn chn ngn ng xong ( y l ting anh,
ting php, ting vit):

276

-Bn xem 3 tp tin strings.xml 3 ngn ng khc nhau (nh l phi cng id):

- Xem XML layout:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#80FFFF" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

- Xem coding:
1
2
3
4

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
277

5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv=(ListView) findViewById(R.id.listView1);
ArrayAdapter<String>adapter=new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.myarray));
lv.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

- By gi bn ch cn vic i chuyn ngn ng trong Setting l xong, t nhin n s ly ng XML


resource ngn ng m bn to.
- Bn ti coding mu y: http://www.mediafire.com/?owbph611tqxtt50
- Bi tp ny khng kh, cc bn ch cn lm theo hng dn.
- Bi tp sau cc bn s hc v x l tp tin trong Android, cng kh quan trng v hay, cc bn hy
ch theo di.

278

Bi tp 28: X l tp tin trong Android


- Bi tp ny Ti s hng dn cc bn cch x l tp tin trong Android, bao gm:
+ Internal Storage
+ External Storage
+ Saving Cache Files
- Cc bn ch l Android s dng cu trc tp tin ging nh trong ng dng Java thun ty.
- Tp tin trong Android c th c lu tr trong Main Memory (thng l lu tr tp tin c dung
lng nh) hoc SD Card (thng l lu tr tp tin c dung lng ln).
- Cc tp tin c lu tr cng vi cc ti nguyn khc trong b nh trong (chng hn nh Icons,
hnh nh, nhc,) th ngi ta gi chung l Resource Files.
- Trn mng c y ry website hng dn v thao tc vi tp tin trong Android, nhng y Ti
mun trnh by theo cch ca Ti.
1) Internal Storage
- y c 2 trng hp:
- Th nht: c Resource File (Read only)
- Th nh : c v ghi tp tin (Read & Write).
* c Resource File:
- Bn xem giao din bn di: Ti to 1 tp tin v nhp i vo mt s d liu ri ko th tp tin
vo th mc drawable. Nu nh ng dng ca bn khng c th mc ny th bn t to n nh l
vit y x drawable, tn file cng ng khong trng, ng ch s ng trc.

279

- Khi nhn chn Read Data, chng trnh s c ni dung t myfile.txt v hin th ln EditText.
- y Ti mun hi cc bn l : Ti sao cc resource c ng gi trong APK li l Read
Only?. Ti ngh cu tr li n gin nht l s dng ti u b nh. V in thoi khng ging
nh my tnh, b nh trong ca n khng c bao la bt ngt nh PC, mi phn mm (.APK) c ci
t vo th n s khng mun Co Gin dung lng v n cn qun l phn mm ti u nht (s
dng b nh t nht).
- Bn xem cu trc XML ca giao din (activity_main.xml):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/btnreaddata"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Read Data" />
<EditText
android:id="@+id/editdata"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="2"
android:ems="10"
android:gravity="top|left"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>

- y l source code c Resource File:


- Bn ch cn copy on code ny vo s kin ca nt c l xong:
1
2
3
4
5
6
7
8
9
10
11
12

public void readData()


{
String data;
InputStream in=
getResources().openRawResource(R.drawable.myfile);
InputStreamReader inreader=new InputStreamReader(in);
BufferedReader bufreader=new BufferedReader(inreader);
StringBuilder builder=new StringBuilder();
if(in!=null)
{
try
{
280

13
14
15
16
17
18
19
20
21
22
23
24

while((data=bufreader.readLine())!=null)
{
builder.append(data);
builder.append("\n");
}
in.close();
editdata.setText(builder.toString());
}
catch(IOException ex){
Log.e("ERROR", ex.getMessage());
}
}
}

- y Ti khng cung cp source ngun, v n ch c 1 hm x xi . Cc bn ch cn thit k giao


din cho ging nh XML Layout ri copy code vo s kin ca nt nhn l xong.
- Cch c tp tin trong Android y chang nh trong Java thun ty, y bn ch dng lnh s
4:
InputStream in= getResources().openRawResource(R.drawable.myfile);
Dng lnh ny c Resource File v tr v InputStream. Khi c InputStream ri th mi x l s
ging nh Java.
* c v ghi tp tin:
- Trng hp ny bn ko th tp tin vo cu trc th mc nh hnh bn di (dng DDMS):
- Nhn vo nhng vt Ti t mu vng, cc bn ko th vo ng v tr ng dng ca bn.

- XML Resource cho bi tp ny:


281

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/btnreaddata"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Read Data" />
<EditText
android:id="@+id/editdata"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="2"
android:ems="10"
android:gravity="top|left"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btnwritedata"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Write Data" />
</LinearLayout>

- XML resource trn s to giao din nh hnh bn di:

- Source Activity
282

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

package tranduythanh.com;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements
OnClickListener{
Button btnread,btnwrite;
EditText editdata;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnread=(Button) findViewById(R.id.btnreaddata);
btnwrite=(Button) findViewById(R.id.btnwritedata);
editdata=(EditText) findViewById(R.id.editdata);
btnread.setOnClickListener(this);
btnwrite.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId()==R.id.btnreaddata)
{
readData();
}
else if(v.getId()==R.id.btnwritedata)
{
writeData();
}
}
/**
* Hm c tp tin trong Android
* Dng openFileInput trong Android c
* ra FileInputStream
*/
public void readData()
{
try {
FileInputStream in= openFileInput("myfile.txt");
BufferedReader reader=new
BufferedReader(new InputStreamReader(in));
283

55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

String data="";
StringBuilder builder=new StringBuilder();
while((data=reader.readLine())!=null)
{
builder.append(data);
builder.append("\n");
}
in.close();
editdata.setText(builder.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Hm ghi tp tin trong Android
* dng openFileOutput ghi
* openFileOutput to ra FileOutputStream
*/
public void writeData()
{
try {
FileOutputStream out=
openFileOutput("myfile.txt",0);
OutputStreamWriter writer=
new OutputStreamWriter(out);
writer.write(editdata.getText().toString());
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* hm ny l c Resource File, Ti gom chung vo y
*/
public void readData2()
{
String data;
InputStream in= getResources()
.openRawResource(R.drawable.myfile);
InputStreamReader inreader=new InputStreamReader(in);
BufferedReader bufreader=new BufferedReader(inreader);
StringBuilder builder=new StringBuilder();
if(in!=null)
{
try{
while((data=bufreader.readLine())!=null)
{
builder.append(data);
builder.append("\n");
}
in.close();
284

109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124

editdata.setText(builder.toString());
}
catch(IOException ex){
Log.e("ERROR", ex.getMessage());
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

- Bn nhn vo dng lnh 52: FileInputStream in= openFileInput(myfile.txt);


Lnh dng ny m tp tin ln c, n tr v FileInputStream nn mi th s ging nh Java
thun ty.
- Tip tc nhn vo dng lnh 78: FileOutputStream out=openFileOutput(myfile.txt,0);
Lnh dng ny m tp tin ln ghi. i s th 2 Ti l s 0 (MODE_PRIVATE) l mc nh.
Bn c th
dng MODE_APPEND, MODE_WORLD_READABLE,MODE_WORLD_WRITEABLE.
ngha ca mi mode bn c th ln mng tm. Hoc ch cn di chuyn chut vo hm trn l eclipse
t gii thch cho cc bn (nu eclipse bn ci Javadoc).
- Bn ti source code mu phn ny y:
http://www.mediafire.com/download/toi0ht8ht0t5gd3/LearnFileInternalStorage.rar
2. External Storage:
- Phn ny Ti mun hng dn cc bn cch tng tc vi tp tin c lu tr trn SD Card.
- thao tc c trn SD Card, bn phi cp quyn cho ng dng (uses permission)
- va ghi va c trn SD Card th ta phi s dng 2 permission bn di
trongAndroidManifest:
<uses-permission android:name=android.permission.WRITE_EXTERNAL_STORAGE />
<uses-permission android:name=android.permission.READ_EXTERNAL_STORAGE />
- ly c ng dn ca SD Card ta dng lnh:
String sdcard=Environment.getExternalStorageDirectory().getAbsolutePath();
285

- Sau mi th tng tc vi tp tin th y x nh Java thun ty, y Ti dng Scanner c


v OutputStreamWriter ghi.
- V vy giao din Ti lm y chang nh Internal Storage:
- Bn to Project v ko th tp tin vo SD card (d nhin khi to AVD th bn phi checked vo
using SD card th mi c). Bn xem hnh bit cch ko th vo SD Card:

- hnh trn bn vo DDMS, ti th mc mnt/ chn sdcard. Phi chn cho ng v n c nhiu th
mc cng tn sdcard, nhng bn chn sdcard trong th mc mnt thi. Sau ko th tp tin vo
y l xong.
- XML Resource y x nh phn internal Storage nn Ti khng a vo y, bn xem Source code
Activity:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

package tranduythanh.com;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements
OnClickListener{
Button btnread,btnwrite;
EditText editdata;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
286

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

setContentView(R.layout.activity_main);
btnread=(Button) findViewById(R.id.btnreaddata);
btnwrite=(Button) findViewById(R.id.btnwritedata);
editdata=(EditText) findViewById(R.id.editdata);
btnread.setOnClickListener(this);
btnwrite.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId()==R.id.btnreaddata)
{
readData();
}
else if(v.getId()==R.id.btnwritedata)
{
writeData();
}
}
/*
* c t SD Card
*
Environment.getExternalStorageDirectory().getAbsolutePath()
* ly ng dn trn SD Card
*/
public void readData()
{
String sdcard=Environment
.getExternalStorageDirectory()
.getAbsolutePath()+"/myfile.txt";
try {
Scanner scan=new Scanner(new File(sdcard));
String data="";
while(scan.hasNext())
{
data+=scan.nextLine()+"\n";
}
scan.close();
editdata.setText(data+"");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* ghi tp tin trn SD Card
*/
public void writeData()
{
String sdcard=Environment
.getExternalStorageDirectory()
.getAbsolutePath()+"/myfile.txt";
try {
OutputStreamWriter writer=
new OutputStreamWriter(
new FileOutputStream(sdcard));
writer.write(editdata.getText()+"");
writer.close();
287

81
82
83
84
85
86
87
88
89
90
91
92
93
94

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

- V c s dng Permission nn bn xem AndroidManifest:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="tranduythanh.com"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="tranduythanh.com.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

- Khi thc thi ng dng, bn s c giao din nh trnh by trn, vi kt qu nh mong mun.
288

- Bn c th ti coding mu y:
http://www.mediafire.com/download/1ydvjc8wvizzjcm/LearnFileExternalStorage.rar
3) Saving cache files:
- Li ch ca cache files l g? tng tc x l ca ng dng khi bn thng xuyn truy cp
internet th bn nn lu cache.
- Khi lu cache th n s u trong in thoi? bn xem hnh:

- Khi lu cache th mc nh n s lu vo th mc cache nh hnh bn trn. Hnh trn Ti c tp tin


tn l myCachefile.Cache.
- Lu nh th no? v xa nh th no?
Khi bn lu cache, Android thng ch cho ti a file cache l 1MB, khi bn g b phn mm th n
cng t ng xa cache ca phn mm ny i.
- ly c ng dn ca th mc Cache trong ng dng, ta dng lnh : getCacheDir() . Sau
cch lu cache tng t nh Java thun ty.
- Di y l phn mm minh ha Cache, giao din tng t nh trn:
- XML resource:
1
2
3
4
5
6
7
8
9
10
11

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/btncreatecache"
289

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Create Cache" />
<EditText
android:id="@+id/editdata"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="2"
android:ems="10"
android:gravity="top|left"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btnreadcache"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Read Cache" />
</LinearLayout>

- X l code Activity:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

package tranduythanh.com;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements
OnClickListener{
Button btncreatecache,btnreadcache;
EditText editdata;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btncreatecache=(Button) findViewById(R.id.btncreatecache);
btnreadcache=(Button) findViewById(R.id.btnreadcache);
editdata =(EditText) findViewById(R.id.editdata);
290

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

btncreatecache.setOnClickListener(this);
btnreadcache.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.btncreatecache)
{
createCache();
}
else if(v.getId()==R.id.btnreadcache)
{
readCache();
}
}
/**
* Ly ton b file cache
*/
public void loadAllCache()
{
File pathCacheDir = getCacheDir();
File []listCache= pathCacheDir.listFiles();
for(File f :listCache)
{
//process f here
f.delete();
}
}
/**
* c cache file
* getCacheDir() tr v ng th mc cache
*/
public void readCache() {
try {
File pathCacheDir = getCacheDir();
String strCacheFileName = "myCacheFile.cache";
File newCacheFile = new
File(pathCacheDir, strCacheFileName);
Scanner sc=new Scanner(newCacheFile);
String data="";
while(sc.hasNext())
{
data+=sc.nextLine()+"\n";
}
editdata.setText(data);
sc.close();
291

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* Lu cache file
*/
public void createCache()
{
try {
File pathCacheDir = getCacheDir();
String strCacheFileName = "myCacheFile.cache";
String strFileContents = editdata.getText()+"";
File newCacheFile = new
File(pathCacheDir, strCacheFileName);
newCacheFile.createNewFile();
FileOutputStream foCache =
new FileOutputStream(
newCacheFile.getAbsolutePath());
foCache.write(strFileContents.getBytes());
foCache.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

- V giao din v cch chy tng t nh v d trc nn Ti khng chp hnh minh ha,
- Bn c th ti coding mu
y: http://www.mediafire.com/download/u0smn6v68xf6uc5/LearnCacheFile.rar
- Nh vy ti gii thiu xong tng tc tp tin trong Android: internal Storage, external storage,
caching file
- Trong bi tp k tip Ti s hng dn cc bn cch tng tc vi XML file trong Android, trong
bi tp ny Ti mun trnh by v 2 k thut duyt tp tin XML l : DOM v SAX. Ti thy n
rt hay, cc bn nn ch theo di.

292

Bi tp 29: XML Parser trong Android


- Tip tc chui x l tp tin trong Android, bi tp ny Ti mong mun cc bn s lm c nhng
cng vic sau:
1) Bit cch to XML (tt nhin rt nhiu bn bit n t lu)
2) Bit cch s dng XML
3) Bit cch duyt XML bng k thut DOM
4) Bit cch duyt XML bng k thut SAX.
- D nhin bn phi thc hin c 2 bi v d bn di th mi c th ni l hiu v XML trong
Android.
-Extensible Markup Language (XML): Cc bn xem chi tit
ti http://www.w3schools.com/xml/default.asp
A)K thut dng DOM:
- DOM (Document Object Model ): Cache all c ch ca n l c ton b ni dung tp tin XML
vo b nh (do nu XML ln th lm chm chng trnh v c th phung ph b nh v khng
phi lc no ta cng mun c ht ni dung XML).
- DOM cho php ly: NodeLists, .getElementsByTagName() , .item(i), .getName() , .getValue() ,
.getFirstChild() , .getAttributes(),
Ta lt qua v d ny (cn dng DOM c XML bn di ln EditText):

293

- Ta i vo cc bc c th c c tp tin XML bng DOM nh sau:

Bc 1:
c th s dng c k thut DOM trong Android, chng ta import cc th vin sau (k c nhng
th vin bt li):
1
2
3
4
5
6
7
8
9
10
11
12

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

- Cc bn ch l trong qu trnh vit code trong Eclipse, n s t import tt c cc th vin trn


gim ta (Bn khng phi g import dng no c).
Bc 2:
To i tng DocumentBuilder (builder ) bng lnh di y:
1
2

DocumentBuilderFactory
fac=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=fac.newDocumentBuilder();

Bc 3:
To FileInputStream t tp tin XML ngun ( y Ti XML ngun trong SD Card):
1
2
3

String
sdcard=Environment.getExternalStorageDirectory().getAbsolutePath();
String xmlfile=sdcard+"/employee.xml";
FileInputStream fIn=new FileInputStream(xmlfile);

Bc 4:
Dng phng thc parse ca i tng builder bc 2 to Document
1

Document doc=builder.parse(fIn);

Bc 5:
294

Ta da vo i tc doc c to ra bc 4 duyt tng node trong XML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Element root= doc.getDocumentElement(); //ly tag Root ra


NodeList list= root.getChildNodes();// ly ton b node con
ca Root
String datashow="";//bin lu thng tin
for(int i=0;i<list.getLength();i++) // duyt t node u
tin cho ti node cui cng
{
Node node=list.item(i);// mi ln duyt th ly ra 1 node
if(node instanceof Element) // kim tra xem node c phi
l Element hay khng, v ta da vo element ly d liu
bn trong
{
Element employee=(Element) node;// ly c tag Employee ra
String id=employee.getAttribute("id");//id l thuc tnh
ca tag Employee
String title=employee.getAttribute("title");//title l
thuc tnh ca tag employee
NodeList listChild=
employee.getElementsByTagName("name");// ly tag name bn
trong ca tag Employee
String name=listChild.item(0).getTextContent();//ly ni
dung ca tag name
listChild=employee.getElementsByTagName("phone");// ly tag
phone bn trong ca tag Employee
String phone=listChild.item(0).getTextContent();// ly ni
dung ca tag phone</span>
datashow+=id+"-"+title+"-"+name+"-"+phone+"\n--------\n";//lu vo bin lu thng tin
}
}
//ta da vo datashow hin th ln giao din

- Bn c th ti code mu
y:http://www.mediafire.com/download/04q4rlg33nmrina/LearnXMLParser_DOM.rar (Ti c nh
km employee.xml trong project ny, bn ch vic ko th n vo SD Card trong my ca bn l ok).

B) k thut dng SAX:


Cng vi v d mc A, nhng Ta s vit theo k thut SAX.
- Simple API for XML , scan the document , tn b nh , Chy nhanh , vit phc tp hn DOM
- Cc tag l element trong SAX c th dng cc hm:
.getAttributeCount()
.getAttributeName()
295

.getAttributeValue()

-S dng XmlPullParser scan ti liu:

- Bc 1:
- Ta cn import cc th vin sau:
1
2
3
4
5
6
7

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

- Ta cng khng phi g tng dng import m eclipse t ng import gim.


- Bc 2:
To i tng parser t class XmlPullParser
1
2

XmlPullParserFactory fc=XmlPullParserFactory.newInstance();
XmlPullParser parser= fc.newPullParser();
296

- Bc 3:
- To FileInputStream t xml source (XML trong SD Card)
1
2
3
4

String sdcard=Environment.
getExternalStorageDirectory().getAbsolutePath();
String xmlfile=sdcard+"/employee.xml";
FileInputStream fIn=new FileInputStream(xmlfile);

- Bc 4:
- Tin hnh duyt
parser.setInput(fIn, "UTF-8");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

int eventType=-1;
String nodeName;
String datashow="";
while(eventType!=XmlPullParser.END_DOCUMENT)//cha kt thc
ti liu
{
eventType=parser.next();// bt u duyt
switch(eventType)
{
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.END_DOCUMENT:
break;
case XmlPullParser.START_TAG://l tag m
nodeName=parser.getName();
if(nodeName.equals("employee")){// kim tra ng tag mnh mun
hay khng
datashow+=parser.getAttributeValue(0)+"-";//ly gi tr ca
thuc tnh
datashow+=parser.getAttributeValue(1)+"-";
}
else if(nodeName.equals("name")){
datashow+=parser.nextText()+"-";//ly ni dung tag element
}
else if(nodeName.equals("phone")){
datashow+=parser.nextText()+"-";
}
break;
case XmlPullParser.END_TAG://l tag ng
nodeName=parser.getName();
if(nodeName.equals("employee")){
datashow+="\n----------------\n";
}
break;
}
}
//da vo datashow hin th ln giao din
297

- Bn c th ti code mu y
: http://www.mediafire.com/download/fh22pkib490n7lf/LearnXMLParser_SAX.rar
-Bi tp dnh cho c gi:
- Duyt XML bng DOM v SAX
- Title ca cc tag XML ta a vo Spinner (ch khng a trng lp)
- Cc thng tin khc a vo ListView
- Mi ln chn Title trong Spinner th ch hin th nhng employee theo Title ny trong XML m thi

298

Bi tp 30: Thc hnh v Shared Preferences


Trong bi tp ny Ti s trnh by v cch lu trng thi ca ng dng (lin quan ti Shared
Preferences) v cch to cc mn hnh cu hnh (lin quan ti Shared Preference Change Listeners)

-A- Cch lu trng thi ca ng dng:


Bc 1:
- Gi hm getSharedPreferences, hm ny tr v SharedPreferences v n c 2 i. i s 1 l tn
tp tin lu trng thi, i s 2 l kiu lu. Ch l i s 1 ta ch ghi tn tp tin (khng cn ghi
phn m rng, v phn m rng mc nhin ca n l .xml khi ta lu thnh cng), i s 2 thng ta
l MODE_PRIVATE:
SharedPreferences pre=getSharedPreferences(my_data, MODE_PRIVATE);
Bc 2:
- To i tng Editor cho php chnh sa d liu:
SharedPreferences.Editor edit=pre.edit();
Bc 3:
- a d liu mun lu tr vo edit bng cc phng thc edit.putXXX(key,value);
Ty vo kiu d liu ta mun lu tr m XXX c thay th bi cc kiu d liu ph hp:
editor.putString(user, drthanh);
editor.putString(pwd, hoilamgi);
editor.putBoolean(checked, true);
Bc 4:
- Lu trng thi bng cch gi dng lnh:
editor.commit();

Sau khi bn lm ng 4 bc trn th chng trnh s lu c trng thi, nh trn ni mc nh


phn m rng l .xml (tc l trng thi c lu di nh dng tp tin XML). Bn trn ta t tn
299

l my_data c ngha l chng trnh s to ra tp tin my_data.xml (bn m DDMS ln xem) t


ng n s lu vo th mc shared_prefs nh hnh bn di:

-B- Cch c trng thi lu:


Rt n gin
Bc 1:
- Gi hm getSharedPreferences tr v i tng SharedPreferences (ging nh phn lu trng
thi m Ti ni trn)
SharedPreferences pre=getSharedPreferences (my_data,MODE_PRIVATE);
Bc 2:
- Gi cc phng thc getXXX(key,gi tr mc nh) ly cc gi tr lc trc c lu
boolean bchk=pre.getBoolean(checked, false); //i s 2 Ti false l gi tr mc nh khi n tm
khng thy key =checked
String user=pre.getString(user, );//ly gi tr c lu trong key=user, nu khng thy th gn
gi tr mc nh l chui rng
String pwd=pre.getString(pwd, );//ging trn

******** Gi *******

300

- Lu v c trng thi bn nn vit thnh cc hm ring bit cho d s dng


- Hm lu bn gi trong s kin onPause
- Hm c bn gi trong s kin onResume.
- ng hi ti v sao???? s b 0 im l do l Ti gii thch r bi tp 5v bi tp 6 ri. Bn t
xem li.
******** END *******
Ti s lm v d c th di y bn hiu r hn v l thuyt:
V d 1: bn mun to mt mn hnh ng nhp c checkbox cho php lu li thng tin ng nhp,
ln sau khi i li th n s ly li thng tin nhp lc trc ngi s dng phi mt cng nhp
li (bit v Shared Preferences), xem hnh mnh ha:

- Khi chn nt ng nhp, chng trnh s ng Activity hin ti v hin th Activity di y:

- Chn nt Thot, chng trnh tip tc ng Activity ny gip tt hn cc Activity trong ng dng.
- Khi ng li chng trnh s phi t ng load li thng tin ng nhp trc (Nu khi ng
nhp c chn Lu thng tin).
- Bn xem cu trc ca Project:

301

- Layout XML ca mn hnh chnh (activity_main.xml):


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#80FFFF"
android:gravity="center"
android:text="ng nhp h thng" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
302

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User:" />
<EditText
android:id="@+id/editUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pasword:" />
<EditText
android:id="@+id/editPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<CheckBox
android:id="@+id/chksaveacount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="Lu thng tin" />
303

81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97

</TableRow>
<TableRow
android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnlogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="ng nhp" />
</TableRow>
</TableLayout>
</LinearLayout>

- Layout XML ca activity_dang_nhap_thanh_cong.xml:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".DangNhapThanhCongActivity" >
<TextView
android:id="@+id/txtmsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="20sp" />
<Button
android:id="@+id/btnThoat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Thot" />
</LinearLayout>

- Bn xem Source code MainActivity.java:


1
2
3
4
5
6

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
304

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
public class MainActivity extends Activity {
Button btnlogin;
EditText edituser,editpassword;
CheckBox chksaveaccount;
//t tn cho tp tin lu trng thi
String prefname="my_data";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlogin=(Button) findViewById(R.id.btnlogin);
edituser =(EditText)
findViewById(R.id.editUser);
editpassword=(EditText)
findViewById(R.id.editPassword);
chksaveaccount=(CheckBox)
findViewById(R.id.chksaveacount);
btnlogin.setOnClickListener(
new View.OnClickListener() {
public void onClick(View arg0) {
doLogin();
}
});
}
/**
* hm ng nhp h thng
*/
public void doLogin()
{
finish();//ng mn hnh hin ti
Intent i=new Intent(this, DangNhapThanhCongActivity.class);
//truyn d liu qua mn hnh mi
i.putExtra("user", edituser.getText().toString());
startActivity(i);//m mn hnh mi
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//gi hm lu trng thi y
savingPreferences();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//gi hm c trng thi y
restoringPreferences();
}
/**
* hm lu trng thi
305

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114

*/
public void savingPreferences()
{
//to i tng getSharedPreferences
SharedPreferences pre=getSharedPreferences
(prefname, MODE_PRIVATE);
//to i tng Editor lu thay i
SharedPreferences.Editor editor=pre.edit();
String user=edituser.getText().toString();
String pwd=editpassword.getText().toString();
boolean bchk=chksaveaccount.isChecked();
if(!bchk)
{
//xa mi lu tr trc
editor.clear();
}
else
{
//lu vo editor
editor.putString("user", user);
editor.putString("pwd", pwd);
editor.putBoolean("checked", bchk);
}
//chp nhn lu xung file
editor.commit();
}
/**
* hm c trng thi lu trc
*/
public void restoringPreferences()
{
SharedPreferences pre=getSharedPreferences
(prefname,MODE_PRIVATE);
//ly gi tr checked ra, nu khng thy th gi tr mc
nh l false
boolean bchk=pre.getBoolean("checked", false);
if(bchk)
{
//ly user, pwd, nu khng thy gi tr mc nh l rng
String user=pre.getString("user", "");
String pwd=pre.getString("pwd", "");
edituser.setText(user);
editpassword.setText(pwd);
}
chksaveaccount.setChecked(bchk);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
306

- Bn xem source code DangNhapThanhCongActivity.java:


package tranduythanh.com;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class DangNhapThanhCongActivity extends Activity {
TextView txtMsg;
Button btnThoat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dang_nhap_thanh_cong);
txtMsg=(TextView) findViewById(R.id.txtmsg);
btnThoat=(Button) findViewById(R.id.btnThoat);
btnThoat.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent i=getIntent();
txtMsg.setText("Hello : "+i.getStringExtra("user"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.activity_dang_nhap_thanh_cong,
menu);
return true;
}
}

- Nh vy l xong, bn bit c cch lu trng thi. Ch l lu trng thi ch lu Primitive


Data, khng cho php lu Object Serialize.
- Bn click vo y ti coding
mu: http://www.mediafire.com/download/4e4lyykdukgof82/LearnSharedPreferences.rar

307

-B- cch to Shared Preference Change Listeners to giao din cu hnh:


Bc 1:
- To mt Project Android bt k, sau to thm mt layout PreferenceScreen:

- t tn ty ( y Ti t tn mypreferencelayout)
- Khng ging nh layout bnh thng, preference screen s nm trong th mc xml nh hnh bn
di:

- Tin hnh to Checkbox ging nh trn. (n c nhiu control khc, ty vo nhu cu)
308

Bc 2:
- To Activity cho Prefence layout trn (K tha t PreferenceActivity):

Bc 3:
- Cu hnh Manifest XML cho Preference Activity trn:

Bc 4:
- Tin hnh sa MainActivity s dng Preference Activity (ng
kOnSharePreferenceChangeListener):

- Bn c th xem kt qu nh bn di:
309


V d 2:
- Bn c gng t xem li l thuyt v c coding hiu. V d ny Ti khng gii thch coding.
- Hay bn cn to ra cc mn hnh cu hnh (ging nh mn hnh Setting ca thit b chng hn
cn bit Shared Preference Change Listeners):

310

- Bn ti source code
y: http://www.mediafire.com/download/lg8881lz8jrp1np/Ex_Module3_Bai5.rar

311

Bi tp 31: Cch s dng SQLite trong Android


Bi tp ny Ti s hng dn cc bn cch s dng SQLite trong Android.
Thay v lu tr bng text file, XML hay SharePreference th bn cng c th lu tr thng tin bng
SQLite. SQLite c tch hp sn trong Android SDK.
Trong bi ny cc bn s hc cc phn sau:
1) Cch to / xa mt c s d liu SQLite trong Android
2) Cch to / xa bng trong SQLite
3) Cch thm/ sa/ xa d liu trong bng
4) Cch truy vn d liu trong bng.
- Tt nhin cn rt nhiu chc nng khc, nhng theo Ti cc bn ch cn lm tt 4 phn ny th c
th vit ng dng Android c SQLite mt cch chuyn nghip ri.
- Theo Ti th cc bn nn s dng cng c SQLite
Administrator: http://download.orbmu2k.de/files/sqliteadmin.zip to hon chnh 1 CSDL sau
ko th tp tin vo DDMS cho l (ci ny bn ti v v t to, ri ko th vo DDMS). Cn cc
hng dn di ny Ti mun gip cc bn hiu c su xa bn trong (hng programmer) CSDL
SQLite.
- Gi s cc bn cn to CSDL nh m t di y (qlquanlysinhvien.db):
- Bng Lp hc (tbllop):
tbllop
Tn ct

Kiu d liu

M t

malop

TEXT

Kha chnh

tenlop

TEXT

siso

INTEGER

- Bng sinh vin (tblsinhvien):


312

tblsinhvien
Tn ct

Kiu d liu

M t

masv

TEXT

Kha chnh

tensv

TEXT

malop

TEXT

kha ngoi

- s dng SQLite, bn import th vin sau:


import android.database.sqlite.SQLiteDatabase;
1) Cch to / xa mt c s d liu SQLite trong Android:
- To mi 1 CSDL:

Khi lu thnh cng, n s lu CSDL vo:


/data/data/app/databases/<databasename>
c th:

313

- Nu bn mun lu tr trn SD Card th bt buc bn phi cp quyn ging nh cp ti


nhng bi trc:
<uses-permission android:name=android.permission.WRITE_EXTERNAL_STORAGE />
- Bn ch vic ly ng dn ca SD Card ra ri lu tn CSDL vo ng ng dn SD Card l ok.
(Bn t xem li cc bi tp trc m Ti hng dn cch lm).
- Xa 1 CSDL:

- Nh trn th ta ch cn gi lnh deleteDatabase(tn CSDL). Nu xa thnh cng th tr v true, xa


tht bi tr v false;
2) Cch to / xa bng trong SQLite:
- y cc bn s to 2 bng tbllop v tblsinhvien. Ch l chng c mi rng buc ton vn.
- Bn xem cch to bng lp:

314

- Bn ch l tn i tng database (ch database.execSQL(sql)) l i tng SQLiteDatabase


c to ra bc to CSDL. Bn phi khai bo cho ph hp trong hm ny cng c th truy
sut.
- To bng sinh vin:

- V bng sinh vin c cha kha ngoi tham chiu ti bng lp, nn bn phi ch dng lnh
tham chiu trn.
3) Cch thm/ sa/ xa d liu trong bng:
- Cch thm mt dng d liu vo trong bng:
+ Dng i tng ContentValues a d liu vo bng. i tng ny c cc phng
thc put(tn ct , d liu)
+ Sau gi phng thc insert a i tng (dng ny) vo bng.
+ Bn ch l phng thc insert c rt nhiu loi i s khc nhau, nhng y Ti ch ni 1 loi
n gin nht (cc kiu khc bn t tm hiu thm). Loi m Ti mun cp ti l khng lin
quan g ti kim tra cc iu kin, ch cn a i tng ContentValues vo insert l bn s c
c 1 dng mi:

315

- Nhn vo on code trn, bn thy Ti s dng c 3 ct malop, tenlop, siso ca bng lp hc:
values.put(malop,DHTH7C) ; tc l a gi tr DHTH7C vo ct malop.
- dng lnh database.insert(tbllop,null,values); i s 1 l tn bng, i s 2 bn truyn null, i
s 3 bn truyn i tng values
- Nu thm thnh cng th s tr v gi tr khc -1. Nu bng -1 l tht bi.
- Cch cp nht d liu:
- Ta dng hm update cp nht d liu theo mt iu kin bt k no .
public int update
(String table, ContentValues values,

String whereClause, String[]whereArgs)

- i s 1 l tn bng
- i s 2 l i tng mun chnh sa (vi gi tr mi)
- i s 3 l tp cc iu kin lc (dng du chm hi ? to iu kin lc)
- i s 4 l tp cc gi tr ca iu kin lc (ly theo ng th t)
- Hm ny tr v s dng b nh hng. V d nu c 3 dng b thay i th n tr v 3. nu khng c
dng no b nh hng th n tr v 0.
V d: Ti vit hm chnh sa (bn cng nn tch thnh tng hm ging vy):

316

- Hm trn : i s 1 l m no mun c chnh sa . i s 2 l gi tr mi. C th bng lp ca


chng ta c 3 ct: m lp, tn lp v s s, nhng m Ti ch mun chnh sa Tn lp m thi. Do
bn thy nh vy ( y Ti ch vit khuyt nh vy cc bn hiu rng khng nht thit phi s
dng ht cc ct).
- Xa d liu:
- Ta dng hm delete xa:
public int delete (String table,

String whereClause,

String[] whereArgs)

- i s 1 l tn bng
- i s 2 l tp iu kin lc (dng ? to)
- i s 3 l tp cc gi tr ca iu kin lc
- Hm tr v s dng b nh hng.
- Mun xa ton b d liu trong bng th ta truyn null vo 2 i s cui:

- Mun xa theo 1 m no :

4) Cch truy vn d liu trong bng.


- L thao tc phc tp nht trong truy sut SQLite
- Ta dng Cursor lu tr gi tr tr v ca hm di y:
317

public Cursor query


(String table, String[] columns, String selection, String[] selectionArgs,String groupBy, String h
aving, String orderBy)
Xem bng m t chi tit:
table

The table name to compile the query against.

columns

A list of which columns to return. Passing null will return all columns,
which is discouraged to prevent reading data from storage that isnt
going to be used.

selection

A filter declaring which rows to return, formatted as an SQL WHERE


clause (excluding the WHERE itself). Passing null will return all rows
for the given table.

selectionArgs

You may include ?s in selection, which will be replaced by the values


from selectionArgs, in order that they appear in the selection. The
values will be bound as Strings.

groupBy

A filter declaring how to group rows, formatted as an SQL GROUP


BY clause (excluding the GROUP BY itself). Passing null will cause
the rows to not be grouped.

having

A filter declare which row groups to include in the cursor, if row


grouping is being used, formatted as an SQL HAVING clause
(excluding the HAVING itself). Passing null will cause all row groups
to be included, and is required when row grouping is not being used.

orderBy

How to order the rows, formatted as an SQL ORDER BY clause


(excluding the ORDER BY itself). Passing null will use the default
sort order, which may be unordered.

- y Ti lm v d n gin nht l truy vn khng phi lc theo iu kin no c:


- V d c tt c danh sch lp hc trong bng tbllop:

318

-database.query s tr v mt Cursor, Lc ny Cursor u c cha tr ti dng d liu no c. Do


ta phi gi lnh .moveToFirst Cursor tr u c ti dng u tin. Sau ta dng vng lp while
duyt tng dng d liu. Ch l Cursor ny ging nh Pointer n cho php truy sut ngu nhin.
- Bn c th ti coding mu y ca phn hng dn ny
y: http://www.mediafire.com/download/leuuld4a225tw5c/LearnSQLite.rar
- Bi tp tip theo Ti s yu cu cc bn vit chng trnh qun l sch s dng SQLite bn cng
c thm kin thc v n.

319

Bi tp 32: Tip tc cng c kin thc SQLite,


v d tng hp qun l sch
lm c bi tp 32 ny th bt buc bn phi t ai en bi tp 31 , ng thi bn phi rnh
custom layout, intent Trong bi tp ny Ti ch khng gii thch coding nhiu l cc bn t
suy lun logic, t tng hp li cc kin thc hc c t cc bi tp trc hon thnh bi ny.
V thc ra bi tp ny l kt hp ca tt c cc kin thc trc .
-

Vit chng trnh qun l sch c m t nh sau:

Mt tc gi s c nhiu cun sch, thng tin tc gi gm: m , tn


Mi cun sch thuc v mt nh tc gi no , thng tin mi cun sch gm: m sch, tn
sch, ngy xut bn

Hy chn kiu d liu hp l to c s d liu (s dng SQLite) cho ng vi m t trn

Thit k giao din nh hnh bn di:

Phi to Tc gi trc khi vo chc nng qun l Sch

Khi chn chc nng thm Tc gi, chng trnh s xut hin mn hnh di y (ch m
di dng Dialog):

Chn Lu tc gi lu, chn xa trng xa d liu va nhp, focus ti m.

Khi chn xem danh sch Tc gi, chng trnh s m mt mn hnh mi hin th danh
sch Tc gi to ch dng CustomLayout cho ListView:
320

Khi chn tng tc gi trong danh sch, s hin th mn hnh cho php chnh sa tc gi:

Chn Update cp nht li Tc gi

Khi nhn Tht Lu (Long time) vo tng tc gi trong danh sch, chng trnh s hin th
Alert Dialog hi xem c mun xa Tc gi ny hay khng?

Chn C xa tc gi hin ti,


Chn Khng tr v mn hnh xem danh sch
Khi chn chc nng qun l sch mn hnh chnh chng trnh s hin th:

321

Load danh sch Tc gi vo Spinner


S dng DatePickerDialog ch ngy xut bn
Chn Thm sch lu vo CSDL ng vi tc gi chn trong Spinner, ng thi cp nhp vo
ListView bn di.

Bn xem cu trc th mc ca ng dng:

- Bi ny rt phc tp nn cc bn phi tp trung 12 thnh cng lc nghin cu + ngi thin


tnh tm lm bi nu khng s b Tu Ha Nhp Ma.
- Bn xem activity_main.xml layout Giao din chnh ca chng trnh:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#004000"
android:gravity="center"
android:text="Qun L Sch"
android:textColor="#FFFFFF"
android:textSize="20sp" />
322

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

<Button
android:id="@+id/btnInsertAuthor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Thm Tc Gi" />
<Button
android:id="@+id/buttonShowAuthorList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Xem danh sch Tc Gi" />
<Button
android:id="@+id/buttonInsertBook"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:text="Qun l Sch" />
</LinearLayout>

v Source code x l MainActivity.java:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

package tranduythanh.com;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/**
* hm hnh chnh cho php chn cc thao tc
* @author drthanh
*
*/
public class MainActivity extends Activity {
Button btnCreateDatabase=null;
Button btnInsertAuthor=null;
Button btnShowAuthorList=null;
Button btnShowAuthorList2=null;
Button btnTransaction=null;
Button btnShowDetail=null;
Button btnInsertBook=null;
public static final int OPEN_AUTHOR_DIALOG=1;
323

31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

public static final int SEND_DATA_FROM_AUTHOR_ACTIVITY=2;


SQLiteDatabase database=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnInsertAuthor=(Button) findViewById(R.id.btnInsertAuthor);
btnInsertAuthor.setOnClickListener(new MyEvent());
btnShowAuthorList=(Button)
findViewById(R.id.buttonShowAuthorList);
btnShowAuthorList.setOnClickListener(new MyEvent());
btnInsertBook=(Button) findViewById(R.id.buttonInsertBook);
btnInsertBook.setOnClickListener(new MyEvent());
getDatabase();
}
/**
* hm kim tra xem bng c tn ti trong CSDL hay cha
* @param database - c s d liu
* @param tableName - tn bng cn kim tra
* @return tr v true nu tn ti
*/
public boolean isTableExists(SQLiteDatabase database, String
tableName) {
Cursor cursor = database.rawQuery("select DISTINCT tbl_name
from sqlite_master where tbl_name = '"+tableName+"'", null);
if(cursor!=null) {
if(cursor.getCount()>0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
/**
* hm to CSDL v cc bng lin quan
* @return
*/
public SQLiteDatabase getDatabase()
{
try
{
database=openOrCreateDatabase("mydata.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
if(database!=null)
{
if(isTableExists(database,"tblAuthors"))
return database;
database.setLocale(Locale.getDefault());
database.setVersion(1);
String sqlAuthor="create table tblAuthors ("
+"id integer primary key autoincrement,"
+"firstname text, "
+"lastname text)";
database.execSQL(sqlAuthor);
324

85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

String sqlBook="create table tblBooks ("


+"id integer primary key autoincrement,"
+"title text, "
+"dateadded date,"
+"authorid integer not null constraint authorid references
tblAuthors(id) on delete cascade)";
database.execSQL(sqlBook);
//Cch to trigger khi nhp d liu sai rng buc quan h
String sqlTrigger="create trigger fk_insert_book before insert
on tblBooks "
+" for each row "
+" begin "
+" select raise(rollback,'them du lieu tren bang tblBooks bi
sai') "
+" where (select id from tblAuthors where id=new.authorid) is
null ;"
+" end;";
database.execSQL(sqlTrigger);
Toast.makeText(MainActivity.this, "OK OK",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
return database;
}
public void createDatabaseAndTrigger()
{
if(database==null)
{
getDatabase();
Toast.makeText(MainActivity.this, "OK OK",
Toast.LENGTH_LONG).show();
}
}
/**
* hm m mn hnh nhp Tc gi
*/
public void showInsertAuthorDialog()
{
Intent intent=new Intent(MainActivity.this,
CreateAuthorActivity.class);
startActivityForResult(intent, OPEN_AUTHOR_DIALOG);
}
/**
* hm xem danh sch tc gi dng Activity
* Ti lm 2 cch cc bn n tp li ListView
* bn gi hm no th gi 1 thi showAuthorList1 hoc
showAuthorList2
*/
public void showAuthorList1()
{
Intent intent=new Intent(MainActivity.this,
325

139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192

ShowListAuthorActivity.class);
startActivity(intent);
}
/**
* hm xem danh sch tc gi dng ListActivity
* Ti lm 2 cch cc bn n tp li ListView
* bn gi hm no th gi 1 thi showAuthorList1 hoc
showAuthorList2
*/
public void showAuthorList2()
{
Intent intent=new Intent(MainActivity.this,
ShowListAuthorActivity2.class);
startActivity(intent);
}
/**
* Ti cung cp thm hm ny cc bn nghin cu thm v
transaction
*/
public void interactDBWithTransaction()
{
if(database!=null)
{
database.beginTransaction();
try
{
//lm ci g tm lum y,
//ch cn c li sy ra th s kt thc transaction
ContentValues values=new ContentValues();
values.put("firstname", "xx");
values.put("lastname", "yyy");
database.insert("tblAuthors", null, values);
database.delete("tblAuthors", "ma=?", new String[]{"x"});
//Khi no hm ny c gi th cc thao tc bn trn mi thc
hin c
//Nu n khng c gi th mi thao tc bn trn u b hy
database.setTransactionSuccessful();
}
catch(Exception ex)
{
Toast.makeText(MainActivity.this, ex.getMessage(),
Toast.LENGTH_LONG).show();
}
finally
{
database.endTransaction();
}
}
}
/**
* hm x l kt qu tr v
*/
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
326

193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235

// TODO Auto-generated method stub


super.onActivityResult(requestCode, resultCode, data);
if(resultCode==SEND_DATA_FROM_AUTHOR_ACTIVITY)
{
Bundle bundle= data.getBundleExtra("DATA_AUTHOR");
String firstname=bundle.getString("firstname");
String lastname=bundle.getString("lastname");
ContentValues content=new ContentValues();
content.put("firstname", firstname);
content.put("lastname", lastname);
if(database!=null)
{
long authorid=database.insert("tblAuthors", null, content);
if(authorid==-1)
{
Toast.makeText(MainActivity.this,authorid+" - "+ firstname +" "+lastname +" ==> insert error!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this, authorid+" - "+firstname +" "+lastname +" ==>insert OK!", Toast.LENGTH_LONG).show();
}
}
}
}
/**
* class x l s kin
* @author drthanh
*
*/
private class MyEvent implements OnClickListener
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.btnInsertAuthor)
{
showInsertAuthorDialog();
}
else if(v.getId()==R.id.buttonShowAuthorList)
{
showAuthorList1();
}
else if(v.getId()==R.id.buttonInsertBook)
{
Intent intent=new Intent(MainActivity.this,
InsertBookActivity.class);
startActivity(intent);
}
}
327

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_simple_database_main,
menu);
return true;
}
}
- XML source thm tc gi activity_create_author.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M tc gi:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editTextFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
328

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

android:text="Tn tc gi:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editTextLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/buttonClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Xa trng" />
<Button
android:id="@+id/buttonInsert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lu tc gi" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
</TableLayout>
</LinearLayout>

- Source code x l thm tc gi CreateAuthorActivity.java:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
/**
* class nhp thng tin tc gi
* Mi thay i u gi thng tin v MainActivity x l
* @author drthanh
*
329

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

*/
public class CreateAuthorActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_author);
final Button btnInsert =(Button)
findViewById(R.id.buttonInsert);
final EditText txtFirstname=(EditText)
findViewById(R.id.editTextFirstName);
final EditText txtLastname=(EditText)
findViewById(R.id.editTextLastName);
final Intent intent= getIntent();
btnInsert.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent();
Bundle bundle=new Bundle();
bundle.putString("firstname",
txtFirstname.getText().toString());
bundle.putString("lastname",
txtLastname.getText().toString());
intent.putExtra("DATA_AUTHOR", bundle);
setResult(MainActivity.SEND_DATA_FROM_AUTHOR_ACTIVITY,
intent);
CreateAuthorActivity.this.finish();
}
});
final Button btnClear=(Button) findViewById(R.id.buttonClear);
btnClear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
txtFirstname.setText("");
txtLastname.setText("");
txtFirstname.requestFocus();
}
});
Bundle bundle= intent.getBundleExtra("DATA");
if(bundle!=null && bundle.getInt("KEY")==1)
{
String f2=bundle.getString("getField2");
String f3=bundle.getString("getField3");
txtFirstname.setText(f2);
txtLastname.setText(f3);
btnInsert.setText("Update");
this.setTitle("View Detail");
/*TableRow row=(TableRow) findViewById(R.id.tableRow3);
row.removeViewAt(0);
row.setGravity(Gravity.RIGHT);*/
330

70
71
72
73

}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_create_author,
menu);
return true;
}
}

- XML source thm Sch activity_insert_book.xml:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/TableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tc gi:" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2" />
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tn sch:" />
<EditText
android:id="@+id/editTextTitle"
331

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ngy XB:" />
<EditText
android:id="@+id/editTextDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="date" />
<Button
android:id="@+id/buttonDate"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="..." />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/buttonInsertBook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="3"
android:text="Thm Sch" />
</TableRow>
<TableRow
android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
332

96
97
98
99
100
101
102
103
104

</TableRow>
<ListView
android:id="@+id/listViewBook"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</TableLayout>

- Source code x l thm sch InsertBookActivity.java:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

package tranduythanh.com;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
/**
* class hin th thng tin Tc gi v Spinner
* v hin th thng tin sch vo ListView
* ng thi cho php thao tc vi sch
* Class ny l kh hiu nht, nhng ch l tng hp ca
* cc kin thc hc trc
* @author drthanh
*
*/
public class InsertBookActivity extends Activity {
SQLiteDatabase database=null;
List<InforData>listBook=null;
List<InforData>listAuthor=null;
InforData authorData=null;
MySimpleArrayAdapter adapter=null;
int day,month,year;
@Override
333

43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_book);
Spinner pinner=(Spinner) findViewById(R.id.spinner1);
listAuthor=new ArrayList<InforData>();
InforData d1=new InforData();
d1.setField1("_");
d1.setField2("Show All");
d1.setField3("_");
listAuthor.add(d1);
//Lnh x l a d liu l Tc gi v Spinner
database=openOrCreateDatabase("mydata.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
if(database!=null)
{
Cursor cursor=database.query("tblAuthors", null, null, null,
null, null, null);
cursor.moveToFirst();
while(cursor.isAfterLast()==false)
{
InforData d=new InforData();
d.setField1(cursor.getInt(0));
d.setField2(cursor.getString(1));
d.setField3(cursor.getString(2));
listAuthor.add(d);
cursor.moveToNext();
}
cursor.close();
}
adapter=new MySimpleArrayAdapter(InsertBookActivity.this,
R.layout.my_layout_for_show_list_data,listAuthor);
adapter.setDropDownViewResource(android.R.layout.simple_spi
nner_dropdown_item);
pinner.setAdapter(adapter);
//X l s kin chn trong Spinner
//chn tc gi no th hin th ton b sch ca tc gi
m thi
//Nu chn All th hin th ton b khng phn hit tc gi
pinner.setOnItemSelectedListener(new
OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
if(arg2==0)
{
//Hin th mi sch trong CSDL
authorData=null;
loadAllListBook();
}
else
{
//Hin th sch theo tc gi chn trong Spinner
authorData=listAuthor.get(arg2);
334

97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150

loadListBookByAuthor(authorData.getField1().toString());
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
authorData=null;
}
});
setCurrentDateOnView();
//lnh x l DatePickerDialog
Button bChangeDate=(Button) findViewById(R.id.buttonDate);
bChangeDate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(113);
}
});
//Lnh x l thm mi mt sn phm theo tc gi ang chn
Button btnInsertBook =(Button)
findViewById(R.id.buttonInsertBook);
btnInsertBook.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(authorData==null)
{
Toast.makeText(InsertBookActivity.this, "Please choose an
author to insert", Toast.LENGTH_LONG).show();
return;
}
EditText txtTitle=(EditText)
findViewById(R.id.editTextTitle);
ContentValues values=new ContentValues();
values.put("title", txtTitle.getText().toString());
Calendar c=Calendar.getInstance();
c.set(year, month, day);
SimpleDateFormat dfmt=new SimpleDateFormat("dd-MM-yyyy");
values.put("dateadded",dfmt.format(c.getTime()));
values.put("authorid", authorData.getField1().toString());
long bId=database.insert("tblBooks", null, values);
if(bId>0)
{
Toast.makeText(InsertBookActivity.this, "Insert Book OK",
Toast.LENGTH_LONG).show();
loadListBookByAuthor(authorData.getField1().toString());
}
else
{
Toast.makeText(InsertBookActivity.this, "Insert Book
Failed", Toast.LENGTH_LONG).show();
335

151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204

}
}
});
}
/*
* Hm hin th mi sch trong CSDL
*/
public void loadAllListBook()
{
Cursor cur=database.query("tblBooks", null, null, null,
null, null, null);
cur.moveToFirst();
listBook=new ArrayList<InforData>();
while(cur.isAfterLast()==false)
{
InforData d=new InforData();
d.setField1(cur.getInt(0));
d.setField2(cur.getString(1));
d.setField3(cur.getString(2));
listBook.add(d);
cur.moveToNext();
}
cur.close();
adapter=new MySimpleArrayAdapter(InsertBookActivity.this,
R.layout.my_layout_for_show_list_data, listBook);
ListView lv=(ListView) findViewById(R.id.listViewBook);
lv.setAdapter(adapter);
}
/**
* hm hin th sch theo tc gi
* @param authorid
*/
public void loadListBookByAuthor(String authorid)
{
Cursor cur=database.query("tblBooks", null, "authorid=?",
new String[]{authorid}, null, null, null);
cur.moveToFirst();
listBook=new ArrayList<InforData>();
while(cur.isAfterLast()==false)
{
InforData d=new InforData();
d.setField1(cur.getInt(0));
d.setField2(cur.getString(1));
d.setField3(cur.getString(2));
listBook.add(d);
cur.moveToNext();
}
cur.close();
adapter=new MySimpleArrayAdapter(InsertBookActivity.this,
R.layout.my_layout_for_show_list_data, listBook);
ListView lv=(ListView) findViewById(R.id.listViewBook);
lv.setAdapter(adapter);
}
@Override
protected Dialog onCreateDialog(int id) {
336

205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233

// TODO Auto-generated method stub


if(id==113)
{
return new DatePickerDialog(this, dateChange, year, month,
day);
}
return null;
}
/**
* x l DatePickerDialog
*/
private DatePickerDialog.OnDateSetListener dateChange= new
OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year1, int
monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
year=year1;
month=monthOfYear;
day=dayOfMonth;
EditText eDate=(EditText) findViewById(R.id.editTextDate);
eDate.setText(day+"-"+(month+1)+"-"+year);
}
};
/**
* thit lp ngy thng nm hin ti
*/
public void setCurrentDateOnView()
{
EditText eDate=(EditText) findViewById(R.id.editTextDate);
Calendar cal=Calendar.getInstance();
day=cal.get(Calendar.DAY_OF_MONTH);
month=cal.get(Calendar.MONTH);
year=cal.get(Calendar.YEAR);
eDate.setText(day+"-"+(month+1)+"-"+year);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_insert_book,
menu);
return true;
}
}

- XML Source cho custom layout:


1
2
3
4
5
6

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="left"
337

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.2"
android:gravity="left"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_weight="0.4"
android:gravity="left"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
&nbsp;
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_weight="0.4"
android:text="Medium Text"
android:gravity="left"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>

- Source code x l Custom layout InforData.java:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

package tranduythanh.com;
/**
* class dng chung c d liu hin th ln ListView Sch
v tc gi
* bn c th b class ny vit class khc
* y Ti hi lm bing 1 cht l Ti mun vit 1 Class c
cc kiu Object
* n t hiu mi kiu d liu phi vit li nn bn c
c v kh hiu
* Nhng thi ---> rng ln
* @author drthanh
*
*/
public class InforData {
private Object field1;
private Object field2;
private Object field3;
338

public Object getField1() {


return field1;
}
public void setField1(Object field1) {
this.field1 = field1;
}
public Object getField2() {
return field2;
}
public void setField2(Object field2) {
this.field2 = field2;
}
public Object getField3() {
return field3;
}
public void setField3(Object field3) {
this.field3 = field3;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.field1 +" - " +this.field2 +" - "+this.field3;
}

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
}

- Source code x l Custom layout - MySimpleArrayAdapter.java:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

package tranduythanh.com;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
/**
* class dng custom layout
* dng chung cho hin th Sch v Tc gi
* @author drthanh
*
*/
public class MySimpleArrayAdapter extends
ArrayAdapter<InforData> {
private Activity context;
private int layout;
private List<InforData>list;
public MySimpleArrayAdapter(Context context, int
textViewResourceId,
339

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

List<InforData> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
this.context=(Activity) context;
this.layout=textViewResourceId;
this.list=objects;
}
@Override
public View getView(int position, View convertView, ViewGroup
parent) {
// TODO Auto-generated method stub
LayoutInflater flater=context.getLayoutInflater();
View row=flater.inflate(layout, parent,false);
TextView txt1=(TextView) row.findViewById(R.id.textView1);
TextView txt2=(TextView) row.findViewById(R.id.textView2);
TextView txt3=(TextView) row.findViewById(R.id.textView3);
/*txt1.setTextAlignment(Gravity.LEFT);
txt2.setTextAlignment(Gravity.LEFT);
txt3.setTextAlignment(Gravity.LEFT);*/
InforData data=list.get(position);
txt1.setText(data.getField1()==null?"":data.getField1().toStri
ng());
txt2.setText(data.getField2()==null?"":data.getField2().toStri
ng());
txt3.setText(data.getField3()==null?"":data.getField3().toStri
ng());
if(position==0)
{
row.setBackgroundColor(Color.RED);
}
return row;
}
}

- XML source xem danh sch tc gi layout_show_data.xml:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="@+id/listViewShowData"
android:layout_width="match_parent"
android:layout_height="405dp" >
</ListView>
</LinearLayout>
340

19
20
21
22
23
24

<Button
android:id="@+id/buttonBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
</LinearLayout>

- Source code x l xem danh sch tc gi:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

package tranduythanh.com;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
/**
* class xem danh sch tc gi
* @author drthanh
*
*/
public class ShowListAuthorActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_show_data);
updateUI();
Button btn=(Button) findViewById(R.id.buttonBack);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ShowListAuthorActivity.this.finish();
}
});
}
List<InforData>list=new ArrayList<InforData>();
341

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

InforData dataClick=null;
SQLiteDatabase database=null;
MySimpleArrayAdapter adapter=null;
public void updateUI()
{
database=openOrCreateDatabase("mydata.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
if(database!=null)
{
Cursor cursor=database.query("tblAuthors", null, null, null,
null, null, null);
startManagingCursor(cursor);
InforData header=new InforData();
header.setField1("STT");
header.setField2("M tc gi");
header.setField3("Tn tc gi");
list.add(header);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
InforData data=new InforData();
data.setField1(cursor.getInt(0));
data.setField2(cursor.getString(1));
data.setField3(cursor.getString(2));
list.add(data);
cursor.moveToNext();
}
cursor.close();
adapter=new
MySimpleArrayAdapter(ShowListAuthorActivity.this,
R.layout.my_layout_for_show_list_data, list);
final ListView lv= (ListView)
findViewById(R.id.listViewShowData);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(ShowListAuthorActivity.this,"View -->"+
list.get(arg2).toString(), Toast.LENGTH_LONG).show();
Intent intent=new Intent(ShowListAuthorActivity.this,
CreateAuthorActivity.class);
Bundle bundle=new Bundle();
bundle.putInt("KEY", 1);
bundle.putString("getField1",
list.get(arg2).getField1().toString());
bundle.putString("getField2",
list.get(arg2).getField2().toString());
bundle.putString("getField3",
list.get(arg2).getField3().toString());
intent.putExtra("DATA", bundle);
dataClick=list.get(arg2);
startActivityForResult(intent,
342

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

MainActivity.OPEN_AUTHOR_DIALOG);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener()
{
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View
arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
final InforData data=list.get(arg2);
final int pos=arg2;
Toast.makeText(ShowListAuthorActivity.this, "Edit->"+data.toString(), Toast.LENGTH_LONG).show();
AlertDialog.Builder b=new
Builder(ShowListAuthorActivity.this);
b.setTitle("Remove");
b.setMessage("Xa ["+data.getField2() +" "+data.getField3() +"] h?");
b.setPositiveButton("C", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
int n=database.delete("tblAuthors", "id=?", new
String[]{data.getField1().toString()});
if(n>0)
{
Toast.makeText(ShowListAuthorActivity.this, "Remove ok",
Toast.LENGTH_LONG).show();
list.remove(pos);
adapter.notifyDataSetChanged();
}
else
{
Toast.makeText(ShowListAuthorActivity.this, "Remove not ok",
Toast.LENGTH_LONG).show();
}
}
});
b.setNegativeButton("Khng", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
b.show();
return false;
}
});
}
343

153
154
155
156
157
158
159
160
161
162

}
@Override
protected void onActivityResult(int requestCode, int
resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==MainActivity.SEND_DATA_FROM_AUTHOR_ACTIVITY)
{
Bundle bundle=data.getBundleExtra("DATA_AUTHOR");
String f2=bundle.getString("firstname");
String f3=bundle.getString("lastname");
String f1=dataClick.getField1().toString();
ContentValues values=new ContentValues();
values.put("firstname", f2);
values.put("lastname", f3);
if(database!=null)
{
int n=database.update("tblAuthors", values, "id=?", new
String[]{f1});
if(n>0)
{
Toast.makeText(ShowListAuthorActivity.this, "update ok ok ok
", Toast.LENGTH_LONG).show();
dataClick.setField2(f2);
dataClick.setField3(f3);
if(adapter!=null)
adapter.notifyDataSetChanged();
}
}
}
}
}

- Bn c th ti source code y
y: http://www.mediafire.com/download/nf4ghdbr44igpa6/Ex_Module3_Bai6.rar
- Bi tp k tip Ti s hng dn cc bn cch s dng Content Provider c danh b trong in
thoi, cch c lch s cuc gi, cch c Media trong in thoi cng nh bookmark. Bn ch
theo di

344

Bi tp 33: S dng ContentProvider


trong Android
- Bi tp ny Ti s hng dn cc bn cch s dng ContentProvider. C th l cch c danh b,
cch c lch s cuc gi, cch c Media v bookmark.
- Phn ny rt nhiu v phong ph, bn cn khm ph n trn mng nhiu hn.
- Thi gian khng cho php do Ti ch hng dn nhng tnh nng m ta thng xuyn s dng
nht.
- Ti c giao din chnh sau:

- Ta c c php tng qut:


<standard_prefix>://<authority>/<data_path>/<id>
- V d ly tt c cc bookmark trong trnh duyt ta dng c php:
content://browser/bookmarks
- ly ton b danh b trong in thoi ta dng c php:
content://contacts/people
- ly 1 contact theo 1 nh danh no :
content://contacts/people/3
- ly cc kt qu tr v ta cng dng Cursor qun l.
- C 2 cch s dng hm ly kt qu y:
Cch 1:
CursorLoader loader=new CursorLoader(context, uri, null, null, null, null);
345

Cursor c=loader.loadInBackground();
cch 2:
Cursor c = getContentResolver() .query(uri, null, null, null, null);
- Ta s lm c th tng chc nng trong v d trn
- Bn xem cu trc ca bi tp ny:

- Bn xem XML Resource ca mn hnh chnh (activity_main.xml):


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/btnshowallcontact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show All Contact" />
<Button
android:id="@+id/btnaccesscalllog"
android:layout_width="match_parent"
346

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

android:layout_height="wrap_content"
android:text="Access The Call Log" />
<Button
android:id="@+id/btnmediastore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Access Media Store" />
<Button
android:id="@+id/btnaccessbookmarks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Access Bookmarks" />
</LinearLayout>

- Source code x l MainActivity.java:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

package tranduythanh.com;
import android.os.Bundle;
import android.provider.Browser;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.app.Activity;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements
OnClickListener{
Button btnshowallcontact;
Button btnaccesscalllog;
Button btnaccessmediastore;
Button btnaccessbookmarks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnshowallcontact=(Button)
findViewById(R.id.btnshowallcontact);
btnshowallcontact.setOnClickListener(this);
btnaccesscalllog=(Button)
findViewById(R.id.btnaccesscalllog);
btnaccesscalllog.setOnClickListener(this);
347

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89

btnaccessmediastore=(Button)
findViewById(R.id.btnmediastore);
btnaccessmediastore.setOnClickListener(this);
btnaccessbookmarks=(Button)
findViewById(R.id.btnaccessbookmarks);
btnaccessbookmarks.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
Intent intent=null;
if(v==btnshowallcontact)
{
intent=new Intent(this, ShowAllContactActivity.class);
startActivity(intent);
}
else if(v==btnaccesscalllog)
{
accessTheCallLog();
}
else if(v==btnaccessmediastore)
{
accessMediaStore();
}
else if(v==btnaccessbookmarks)
{
accessBookmarks();
}
}
/**
* hm ly danh sch lch s cuc gi
* vi thi gian nh hn 30 giy v sp xp theo ngy gi
*/
public void accessTheCallLog()
{
String [] projection=new String[]{
Calls.DATE,
Calls.NUMBER,
Calls.DURATION
};
Cursor c=getContentResolver().query(
CallLog.Calls.CONTENT_URI,
projection,
Calls.DURATION+"<?",new String[]{"30"},
Calls.DATE +" Asc");
c.moveToFirst();
String s="";
348

90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143

while(c.isAfterLast()==false){
for(int i=0;i<c.getColumnCount();i++){
s+=c.getString(i)+" - ";
}
s+="\n";
c.moveToNext();
}
c.close();
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
/**
* hm c danh sch cc Media trong SD CARD
*/
public void accessMediaStore()
{
String []projection={
MediaStore.MediaColumns.DISPLAY_NAME,
MediaStore.MediaColumns.DATE_ADDED,
MediaStore.MediaColumns.MIME_TYPE
};
CursorLoader loader=new CursorLoader
(this, Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
Cursor c=loader.loadInBackground();
c.moveToFirst();
String s="";
while(!c.isAfterLast()){
for(int i=0;i<c.getColumnCount();i++){
s+=c.getString(i)+" - ";
}
s+="\n";
c.moveToNext();
}
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
c.close();
}
/**
* hm c danh sch Bookmark trong trnh duyt
*/
public void accessBookmarks()
{
String []projection={
Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL,
};
Cursor c=getContentResolver()
.query(Browser.BOOKMARKS_URI, projection,
null, null, null);
c.moveToFirst();
String s="";
int titleIndex=c.getColumnIndex
(Browser.BookmarkColumns.TITLE);
int urlIndex=c.getColumnIndex
(Browser.BookmarkColumns.URL);
while(!c.isAfterLast())
349

{
s+=c.getString(titleIndex)+" - "+
c.getString(urlIndex);
c.moveToNext();
}
c.close();
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}

144
145
146
147
148

}
- Source XML x l xem danh bn (activity_show_all_contact.xml):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ShowAllContactActivity" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<Button
android:id="@+id/btnback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
</LinearLayout>

- Source code x l xem danh b ( ShowAllContactActivity.java):


- Ti vit theo 2 cch : Dng CursorLoader v getContentResolver
1
2
3
4
5
6
7
8
9
10
11
12
13
14

package tranduythanh.com;
import java.util.ArrayList;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
350

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

import android.widget.ListView;
public class ShowAllContactActivity extends Activity {
Button btnback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_all_contact);
btnback=(Button) findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
showAllContacts1();
}
/**
* hm danh ton b danh b
* dng CursorLoader
*/
public void showAllContacts1()
{
Uri uri=Uri.parse("content://contacts/people");
ArrayList<String> list=new ArrayList<String>();
CursorLoader loader=new
CursorLoader(this, uri, null, null, null, null);
Cursor c1=loader.loadInBackground();
c1.moveToFirst();
while(c1.isAfterLast()==false){
String s="";
String idColumnName=ContactsContract.Contacts._ID;
int idIndex=c1.getColumnIndex(idColumnName);
s=c1.getString(idIndex)+" - ";
String
nameColumnName=ContactsContract.Contacts.DISPLAY_NAME;
int nameIndex=c1.getColumnIndex(nameColumnName);
s+=c1.getString(nameIndex);
c1.moveToNext();
list.add(s);
}
c1.close();
ListView lv=(ListView) findViewById(R.id.listView1);
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
/**
* hm danh ton b danh b
* dng getContentResolver
*/
public void showAllContacts2()
{
351

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99

Uri uri=Uri.parse("content://contacts/people");
ArrayList<String> list=new ArrayList<String>();
Cursor c1=getContentResolver()
.query(uri, null, null, null, null);
c1.moveToFirst();
while(c1.isAfterLast()==false)
{
String s="";
String idColumnName=ContactsContract.Contacts._ID;
int idIndex=c1.getColumnIndex(idColumnName);
s=c1.getString(idIndex)+" - ";
String
nameColumnName=ContactsContract.Contacts.DISPLAY_NAME;
int nameIndex=c1.getColumnIndex(nameColumnName);
s+=c1.getString(nameIndex);
c1.moveToNext();
list.add(s);
}
c1.close();
ListView lv=(ListView) findViewById(R.id.listView1);
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if
it is present.
getMenuInflater().inflate(R.menu.activity_show_all_contact,
menu);
return true;
}
}

- Lu cp quyn cho ng dng:


AndroidManifest.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="tranduythanh.com"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.READ_CONTACTS"
/>
<uses-permission
android:name="android.permission.READ_CALL_LOG" />
352

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="com.android.browser.permission.READ_HISTORY_BOOKMA
RKS" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="tranduythanh.com.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="tranduythanh.com.ShowAllContactActivity"
android:label="@string/title_activity_show_all_contact" >
</activity>
</application>
</manifest>

- Dng 11, 12, 13, 14 l cp quyn cho ng dng c th truy sut cc chc nng mong mun.
- By gi bn thc hin ng dng v quan st, gi Ti chy ln v dng chc nng xem ton b danh
b:

- Tng
t nh vy bn th cc chc nng cn li trong ng dng.
- Bn c th ti coding mu y
y: http://www.mediafire.com/download/kaac7d36ocvr8ba/LearnContentProvider.rar
- Bi tp k tip cc bn s c hc v mt k thut hon ton mi trong Android v rt kh v rt
hu dng, l k thut x l a Tin Trnh trong Android. Cc bn phi ch theo di v n v
cng quan trng, n cng ging nh Intent l huyt mch trong cc ng dng ca Android.
353

Bi tp 34: a tin trnh trong Android (MultiThreading)


- Chc mng cc bn vt qua c 33 ca i bi tp Android.
-Ti tht s vui mng xc ng khi cc bn bn b theo di tng bi, ti c y th Ti cam
oan rng cc bn phi tn rt nhiu cng sc v thi gian, cc bn phi thc ngy m lm
c nhng bi tp trc .
- p li nhng c gng ca cc bn, trong bi tp ny Ti s cung cp cho cc bn mt kin thc
hay, kin thc mi v cc k kh cc bn quen vi ni kh au v sau c b kh na th cng
quen ri s khng cn thy kh (Ti vit theo phm tr trit hc, ch c lp trnh qu kh mi hiu).
- Nh Ti tng ni Intent l linh hn ca Android, trong mi ng nghch hm hay mt tin ca
Android th Intent vn tn ti nh cha tng c tn ti.
- Cn a tin trnh (Multi Threading)? n cng vy, n cng ging nh k thut truyn huyt mch
ca tng ng dng Android, c bit l nhng ng dng V i. V d nh bn cn cp nht giao
din lc thi gian thc, bn cn kt ni internet hay lm nhng giao tc no m phi phn ra nhiu
tiu trnh chy. x l c a tin trnh th bn phi c mt t duy lp trnh logic tht tt, nu
khng tt th phi (Ly Cn C B Thng Minh).
- K thut a tin trnh rt kh m khng kh (nu bn hiu).
- Trong bi ny Ti s hng dn cc bn x l a tin trnh vi Handler class v AsyncTask class.

Ti liu tham kho: http://duythanhcse.wordpress.com

354

You might also like