You are on page 1of 129

TRNG I HC KHOA HC T NHIN KHOA CNG NGH THNG TIN

LP TRNH TRN DI NG VI J2ME

GVHD: V TM VN SVTH : TRN C MINH 0112355 V TH TUN 0112411

04/2005

Mc lc
Trang Mc lc ..................................................................................................................................... 2 I.
1. 2. a) b) 3. a) 4. a) b) c) 5.

Gii thiu v J2ME ........................................................................................................... 5


Lch s ...............................................................................................................................................................................5 L do chn J2ME .............................................................................................................................................................5 Java ban u c thit k dnh cho cc my vi ti nguyn b nh hn ch ..............................................................5 Th trng ca J2ME c m rng ra cho nhiu chng loi thit b nh:...................................................................5 Kin trc ca J2ME .........................................................................................................................................................5 Gii thiu cc thnh phn trong nn tng J2ME:...........................................................................................................6 Gii thiu MIDP ...............................................................................................................................................................8 nh ngha: ....................................................................................................................................................................8 Nhng chc nng MIDP khng thc hin c: ...........................................................................................................8 Nhng chc nng MIDP cung cp.................................................................................................................................9 Mi trng pht trin J2ME...........................................................................................................................................9

II.
1. 2. a) b) c) d) e) f) g) 3. a) b) c) d)

Cc thnh phn giao din mc cao ca ng dng MIDP ........................................ 13


i tng Display, Displayable v Screens ..................................................................................................................13 Thnh phn Form v Items ...........................................................................................................................................14 DateField .....................................................................................................................................................................14 Gauge...........................................................................................................................................................................16 StringItem ....................................................................................................................................................................17 TextField......................................................................................................................................................................18 ChoiceGroup................................................................................................................................................................20 Spacer ..........................................................................................................................................................................22 Image and ImageItem ..................................................................................................................................................23 Thnh phn List, Textbox, Alert, v Ticker ................................................................................................................25 List...............................................................................................................................................................................25 TextBox .......................................................................................................................................................................27 Alert v AlertType.......................................................................................................................................................28 Ticker...........................................................................................................................................................................30

III.
1. 2. a)

Cc thnh phn giao din mc thp ca ng dng MIDP ................................... 33


Cc hm API mc thp...............................................................................................................................................33 Lp Canvas .....................................................................................................................................................................33 H thng trc ta ....................................................................................................................................................33

b) c) d) e) f) g) h) 3. a) b) c) d) e) f) g) h) i) 4.

To mt i tng Canvas...........................................................................................................................................34 V trn i tng Canvas ............................................................................................................................................35 S kin hnh ng .......................................................................................................................................................35 M phm.......................................................................................................................................................................36 Cc hnh ng trong x l cc tr chi .......................................................................................................................36 Xc nh cc hnh ng ca tr chi...........................................................................................................................37 S kin con tr .............................................................................................................................................................40 Lp Graphics ..................................................................................................................................................................42 H tr mu...................................................................................................................................................................42 Loi nt v ...................................................................................................................................................................43 V cung........................................................................................................................................................................43 V hnh ch nht..........................................................................................................................................................46 Font ch .......................................................................................................................................................................46 im neo .....................................................................................................................................................................47 V cc chui k t .......................................................................................................................................................48 V nh..........................................................................................................................................................................54 Mt s cc phng thc khc ca lp Graphics ..........................................................................................................57 Cc hm API dng lp trnh Game .........................................................................................................................58

IV.
1. 2. 3.

X l s kin ............................................................................................................... 59
i tng Command......................................................................................................................................................59 i tng Item................................................................................................................................................................60 V d ................................................................................................................................................................................60

V.
1. 2. a) b) c) 3. 4. 5. 6. 7. 8.

Record Management System......................................................................................... 62


Persistent Storage Through the Record Store .............................................................................................................62 Cc vn lin quan n RMS .....................................................................................................................................64 Hn ch v kh nng lu tr ca thit b di ng ........................................................................................................64 Tc truy xut d liu...............................................................................................................................................64 C ch lung an ton ...................................................................................................................................................64 Cc hm API trong RMS...............................................................................................................................................64 Duyt Record vi RecordEnumeration ........................................................................................................................74 Sp xp cc record vi interface RecordComparator .................................................................................................75 Searching with RecordFilter..........................................................................................................................................91 Notification of Changes with RecordListener ............................................................................................................103 Exception Handling ......................................................................................................................................................107

VI.
1.

The Generic Connection Framework....................................................................... 108


Nhng protocol c h tr trong GCF ....................................................................................................................108

2. a) b) 3.

H tr giao thc HTTP trong MIDP ..........................................................................................................................113 Request and response protocols .................................................................................................................................114 The HttpConnection API ...........................................................................................................................................116 Accessing a Java servlet ...............................................................................................................................................122

Ph luc................................................................................................................................................................................... 127

Gii thiu v J2ME

I. Gii thiu v J2ME


1. Lch s J2ME c pht trin t kin trc Java Card, Embeded Java v Personal Java ca phin bn Java 1.1. n s ra i ca Java 2 th Sun quyt nh thay th Personal Java v c gi vi tn mi l Java 2 Micro Edition, hay vit tt l J2ME. ng vi tn gi, J2ME l nn tng cho cc thit b c tnh cht nh, gn:

2. L do chn J2ME a) Java ban u c thit k dnh cho cc my vi ti nguyn b nh hn ch. b) Th trng ca J2ME c m rng ra cho nhiu chng loi thit b nh: Cc lai th c nhn nh Java Card My in thoi di ng My PDA (Personal Digital Assistant - thit b tr gip c nhn) Cc hp iu khin dnh cho tivi, thit b gii tr gia dng

3. Kin trc ca J2ME Phn ny s trnh by kin trc tng qut ca nn tng Java

Trang: 5

Gii thiu v J2ME

a) Gii thiu cc thnh phn trong nn tng J2ME: nh ngha v Configuration (Cu hnh): l c t nh ngha mt mi trng phn mm cho mt dng cc thit b c phn loi bi tp hp cc c tnh, v d nh: Kiu v s lng b nh Kiu v tc b vi x l Kiu mng kt ni Do y l c t nn cc nh sn xut thit b nh Samsung, Nokia bt buc phi thc thi y cc c t do Sun qui nh cc lp trnh vin c th da vo mi trng lp trnh nht qun v thng qua s nht qun ny, cc ng dng c to ra c th mang tnh c lp thit b cao nht c th. V d nh mt lp trnh vin vit chng trnh game cho in thoi Samsung th c th sa i chng trnh ca mnh mt cch ti thiu nht c th chy trn in thai Nokia.. Hin nay Sun a ra 2 dng Configuration: CLDC (Connected Limited Device Configuration-Cu hnh thit b kt ni gii hn): c thit k nhm vo th trng cc thit b cp thp (low-end), cc thit b ny thng thng l my in thai di ng v PDA vi khong 512 KB b nh. V ti nguyn b nh hn ch nn CLDC c gn vi Java khng dy (Java Wireless ), dng nh cho php ngi s dng mua v ti v cc ng dng Java, v d nh l Midlet. CDC- Connected Device Configuration (Cu hnh thit b kt ni): CDC c a ra nhm n cc thit b c tnh nng mnh hn dng thit b thuc CLDC nhng vn yu hn cc h thng my bn s dng J2SE. Nhng thit b ny c nhiu b nh hn (thng thng l trn 2Mb) v c b x l mnh hn. Cc sn phm ny c th k n nh cc my PDA cp cao, in thoi web, cc thit b gia dng trong gia nh C 2 dng Cu hnh k trn u cha my o Java (Java Virtual Machine) v tp hp cc lp (class) Java c bn cung cp mt mi trng cho cc ng dng J2ME. Tuy nhin, bn ch rng i vi cc thit b cp thp, do hn ch v ti nguyn nh b nh v b x l nn khng th yu cu my o h tr tt c cc tnh nng nh vi my o ca J2SE, v d,

Trang: 6

Gii thiu v J2ME cc thit b thuc CLDC khng c phn cng yu cu cc php tnh ton du phy ng, nn my o thuc CLDC khng c yu cu h tr kiu float v double.

Bng di l s so snh cc thng s k thut ca CDC v CLDC CLDC CDC Ram >=32K, <=512K >=256K Rom >=128k, <=512k >=512k Ngun Nng C GiI Hn (ngun pin) Khng gii hn Lng Network Chm Nhanh nh ngha v Profile: Profile m rng Configuration bng cch thm vo cc class b tr cc tnh nng cho tng thit b chuyn bit. C 2 Configuration u c nhng profile lin quan v t nhng profile ny c th dng cc class ln nhau. n y ta c th nhn thy do mi profile nh ngha mt tp hp cc class khc nhau, nn thng ta khng th chuyn mt ng dng Java vit cho mt profile ny v chy trn mt my h tr mt profile khc. Cng vi l do , bn khng th ly mt ng dng vit trn J2SE hay J2EE v chy trn cc my h tr J2ME. Sau y l cc profile tiu biu: Mobile Information Device Profile (MIDP): profile ny s b sung cc tnh nng nh h tr kt ni, cc thnh phn h tr giao din ngi dng vo CLDC. Profile ny c thit k ch yu nhm vo in thai di ng vi c tnh l mn hnh hin th hn ch, dung lng cha c hn. Do MIDP s cung cp mt giao din ngi dng n gin v cc tnh nng mng n gin da trn HTTP. C th ni MIDP l profile ni ting nht bi v n l kin thc c bn cho lp trnh Java trn cc my di ng (Wireless Java)

Trang: 7

Gii thiu v J2ME PDA Profile: tng t MIDP, nhng vi th trng l cc my PDA vi mn hnh v b nh ln hn Foundation Profile: cho php m rng cc tnh nng ca CDC vi phn ln cc th vin ca b Core Java2 1.3 Ngoi ra cn c Personal Basis Profile, Personal Profile, RMI Profile, Game Profile.

4. Gii thiu MIDP a) nh ngha: y l Profile c nh ngha dnh ring cho cc thit b di ng v l thnh phn chnh trong J2ME. MIDP cung cp cc chc nng c bn cho hu ht cc dng thit b di ng ph bin nht nh cc my in thoI di ng v cc my PDA. Tuy nhin MIDP khng phi l cy a thn cho mi lp trnh vin v nh chng ta bit, MIDP c thit k cho cc my di ng c cu hnh rt thp. Trong phn sau ti s lit k qua cc tnh nng m MIDP cung cp v nhng gii hn ca n. b) Nhng chc nng MIDP khng thc hin c: Php tnh du phy ng (floating point): Php tnh ny i hi rt nhiu ti nguyn CPU v phn ln cc CPU cho cc thit b di ng khng h tr php tnh ny, do MIDP cng khng c. B np class (Class Loader). H tr t kha finalize() nh trong J2SE: Vic dn dp ti nguyn trc khi n b xa c y v pha cc lp trnh vin. Khng h tr JNI H tr hn ch thao tc bt li. Phn ln cc th vin API cho Swing v AWT khng th s dng c trong MIDP. Khng h tr cc tnh nng qun l file v th mc: y c th lm bn ngc nhin nhng thc t l cc thit b J2ME khng c h tr cc thit b lu tr thng thng nh cng v.v. Tuy nhin, iu khng c ngha l bn phi mt i mi d liu quan trng mi khi tt my, Sun cung cp mt chc nng khc tng ng gi l Record Management system (RMS) cung cp kh nng lu tr cho cc thit b ny.

Trang: 8

Gii thiu v J2ME

c) Nhng chc nng MIDP cung cp Cc lp v kiu d liu: Phn ln cc lp m cc lp trnh vin Java quen thuc vn cn c gi li v d nh cc lp trong gi java.util nh Stack, Vector v Hastable cng nh Enumeration. H tr i tng Display: ng nh tn gi mt chng trnh MIDP s h tr duy nht mt i tng Display l i tng qun l vic hin th d liu trn mn hnh in thoi. H tr Form v cc giao din ngi dng. H tr Timer v Alert Cung cp tnh nng Record Management System (RMS) cho vic lu tr d liu

Ngoi ra vo thng 11 nm 2003 Sun tung ra MIDP 2.0 vi hng lot tnh nng khc c cung cp thm so vi bn 1.0. Nhng ci tin ni bt so vi MIDP 1.0 Nng cp cc tnh nng bo mt nh o Download qua mng an ton hn qua vic h tr giao thc HTTPS. o Kim sot vic kt ni gia my di ng v server: v d nh cc chng trnh khng th kt ni ti server nu thiu s chp thun ca ngi s dng. Thm cc API h tr Multimedia. Mt trong nhng ci tin hp dn nht ca MIDP 2.0 l tp cc API media ca n. Cc API ny l mt tp con ch h tr m thanh ca Mobile Media API (MMAPI). M rng cc tnh nng ca Form. Nhiu ci tin c a vo API javax.microedition.lcdui trong MIDP 2.0, nhng cc thay i ln nht (ngoi API cho game) l trong Form v Item. H tr cc lp trnh vin Game bng cch tung ra Game API: C l Sun kp nhn ra th trng y tim nng ca cc thit b di ng trong lnh vc Game. Vi MIDP 1.0 th cc lp trnh vin phi t mnh vit code qun l cc hnh ng ca nhn vt cng nh qun l ha. Vic ny s lm tng kch thc file ca sn phm cng nh vic xut hin cc on m b li. c hng li nht t Game API trong MIDP 2.0 khng ch l cc lp trnh vin Game m cn l cc lp trnh vin cn s dng cc tnh nng ha cao cp. tng c bn ca Game API l vic gi nh rng mt mn hnh game l tp hp cc layer (lp). V d nh: trong mt game ua xe th mn hnh nn l mt layer, con ng l mt layer v chic xe c xem nh ang nm trn layer khc. Vi Game API nh pht trin cn c cung cp cc tnh nng nh qun l cc thao tc bn phm. H tr kiu nh RGB: mt trong nhng ci tin hp dn cho cc nh pht trin MIDP l vic biu din hnh nh di dng cc mng s nguyn, cho php MIDlet thao tc vi d liu hnh nh mt cch trc tip. 5. Mi trng pht trin J2ME C nhiu mi trng pht trin ng dng J2ME v mi hng in thoi cng a ra nhng mi trng pht trin cho ring mnh. y ti s gii thiu toolkit ca Sun: J2ME Wireless Toolkit. a ch download chng trnh: http://java.sun.com/j2me/download.html. Ngoi ra bn cn phi c J2SDK 1.4 tr ln. Trang: 9

Gii thiu v J2ME

Sau khi ci t bn chy chng trnh ti:

Giao din ca chng trnh:

Sau khi hon thnh cc cc bc trn, y l lc bt u vit nhng dng code u tin. Bn nhp chut vo nt bm New Project v nhp vo tn Project v Class m bn mun to, v d TestMidlet.

Trang: 10

Gii thiu v J2ME Ch l bn khng nht thit phi to trng tn class vi tn Project. Trn ca s chng trnh s hin th cc thng bo v vic to cc th mc phc v cho vic xy dng v thc thi m chng trnh

Hy th mc : E:\WTK22\apps\Example\src, y s l ni cha source ca ng dng. Bn c th dng bt k chng trnh son tho vn bn no son code:
import javax.microedition.lcdui.*; import javax.microedition.midlet.*; public class TestMidlet extends MIDlet implements CommandListener { private Form mMainForm; public TestMidlet() { mMainForm = new Form("Lap trinh voi J2ME"); mMainForm.append(new StringItem(null, "Hello world!, MIDP!")); mMainForm.addCommand(new Command("Exit", Command.EXIT, 0)); mMainForm.setCommandListener(this); } public void startApp() { Display.getDisplay(this).setCurrent(mMainForm); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s) { notifyDestroyed(); } }

Sau copy source ny vo th muc ni trn. Ri tin hnh build v run chng trnh Trang: 11

Gii thiu v J2ME

Vng i ca mt MIDlet Ging nh dng chng trnh Applet trn J2SE, mt Midlet lun lun k tha javax.microedition.midlet Hm c bn nht trong mi Midlet l startApp(), hm ny s khi to Midlet cng nh vn hnh cc thnh phn hoc i tng khc, ngoi startApp(), mi Midlet cn c pauseApp() v destroyApp(), mi hm ny s c gi thc thi tng ng khi user chn dng hoc thot chng trnh.

Trang: 12

Cc thnh phn giao din mc cao

II. Cc thnh phn giao din mc cao ca ng dng MIDP


1. i tng Display, Displayable v Screens Mt ng dng MIDlet ch c 1 i tng th hin Display. i tng ny dng ly thng tin v i tng trnh by, v d mu c h tr, v bao gm cc phng thc yu cu cc i tng c trnh by. i tng Display cn thit cho b qun l vic trnh by trn thit b iu khin thnh phn no s c hin th ln trn thit b Mc d ch c mt i tng Display ng vi mi MIDlet, nhng nhiu i tng trong mt MIDlet c th c hin th ra trn thit b nh Forms, TextBoxes, ChoiceGroups, .. Mt i tng Displayable l mt thnh phn c hin th trn mt thit b. MIDP cha 2 lp con ca lp Displayable l Screen v Canvas. Hnh di y m t mi quan h trn

Mt i tng Screen khng phi l mt ci g hin ra trn thit b, m lp Screen ny s c tha k bi cc thnh phn hin th mc cao, chnh cc thnh phn ny s c hin th ra trn mn hnh. Hnh di y s m t mi quan h ca lp Screen v cc thnh phn th hin mc cao.

Trang: 13

Cc thnh phn giao din mc cao Tm li, phn ny ch gii thiu h thng phn cp i tng dng th hin giao din ngi dng trong MIDP. 2. Thnh phn Form v Items Trong phn ny s gii thiu cc thnh phn c hin th ra trn mt Form. Mt Form ch n gin l mt khung cha cc thnh phn, m mi thnh phn c tha k t lp Item. Chng ta s xem qua cc thnh phn hin th trn thit b trn:
DateField Gauge StringItem TextField ChoiceGroup Spacer CustomItem Image and ImageItem

a) DateField
Thnh phn DateField cung cp mt phng tin trc quan thao tc i tng Date c nh ngha trong java.util.Date. Khi to mt i tng DateField, bn cn ch r l ngi dng ch c th chnh sa ngy, chnh sa gi hay ng thi c hai. Cc phng thc dng ca lp DateField gm:
DateField(String label, int mode) DateField(String label, int mode, TimeZone timeZone)
Cc mode tng ng ca lp DateField gm:

DateField.DATE_TIME: cho php thay i ngy gi DateField.TIME: ch cho php thay i gi DateField.DATE: ch cho php thay i ngy

V d:
private DateField dfAlarm; // To mt i tng DateField vi nhn, cho php thay i c ngy v gi dfAlarm = new DateField("Set Alarm Time", DateField.DATE_TIME); dfAlarm.setDate(new Date());

Di y l on chng trnh mu th nghim i tng DateField


import java.util.*; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.util.Timer; import java.util.TimerTask; public class DateFieldTest extends MIDlet implements CommandListener { private Display display; // Reference to display object private Form fmMain; // Main form private Command cmExit; // Exit MIDlet private DateField dfAlarm; // DateField component ItemStateListener,

Trang: 14

Cc thnh phn giao din mc cao

public DateFieldTest() { display = Display.getDisplay(this); // The main form fmMain = new Form("DateField Test"); // DateField with todays date as a default dfAlarm = new DateField("Set Alarm Time", DateField.DATE_TIME); dfAlarm.setDate(new Date()); // All the commands/buttons cmExit = new Command("Exit", Command.EXIT, 1); // Add to form and listen for events fmMain.append(dfAlarm); fmMain.addCommand(cmExit); fmMain.setCommandListener(this); fmMain.setItemStateListener(this); } public void startApp () { display.setCurrent(fmMain); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void itemStateChanged(Item item) { System.out.println("Date field changed."); } public void commandAction(Command c, Displayable s) { if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } }

Trang: 15

Cc thnh phn giao din mc cao

b) Gauge
Mt thnh phn Gauge l mt kiu giao din thng c dng m t mc hon thnh mt cng vic. C 2 loi Gauge l loi tng tc v loi khng tng tc. Loi u cho php ngi dng c th thay i Gauge, loi 2 th i hi ngi pht trin phi cp nht Gauge Di y l hm dng ca lp Gauge:
Gauge(String label, boolean interactive, int maxValue, int initialValue)

V d:
private Gauge gaVolume; // iu chnh m lng gaVolume = new Gauge("Sound Level", true, 100, 4);

Di y l on chng trnh mu minh ha cch s dng lp Gauge


import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class InteractiveGauge extends MIDlet implements CommandListener { private Display display; // Reference to display object private Form fmMain; // The main form private Command cmExit; // Exit the form private Gauge gaVolume; // Volume adjustment public InteractiveGauge() { display = Display.getDisplay(this); // Create the gauge and exit command gaVolume = new Gauge("Sound Level", true, 50, 4); cmExit = new Command("Exit", Command.EXIT, 1); // Create form, add commands, listen for events fmMain = new Form(""); fmMain.addCommand(cmExit); fmMain.append(gaVolume); fmMain.setCommandListener(this); } // Called by application manager to start the MIDlet. public void startApp() { display.setCurrent(fmMain); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s)

Trang: 16

Cc thnh phn giao din mc cao


{ if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } }

c) StringItem
Mt thnh phn StringItem c dng hin th mt nhn hay chui vn bn. Ngi dng khng th thay i nhn hay chui vn bn khi chng trnh ang chy. StringItem khng nhn ra s kin Phng thc dng ca lp StringItem
StringItem(String label, String text)

Di y l on m minh ha vic s dng i tng StringItem


import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class StringItemTest extends MIDlet implements CommandListener { private Display display; // Reference to Display object private Form fmMain; // Main form private StringItem siMsg; // StringItem private Command cmChange; // Change the label and message private Command cmExit; // Exit the MIDlet public StringItemTest() { display = Display.getDisplay(this); // Create text message and commands siMsg = new StringItem("Website: ", "www.IBM.com"); cmChange = new Command("Change", Command.SCREEN, 1); cmExit = new Command("Exit", Command.EXIT, 1); // Create Form, add Command and StringItem, listen for events fmMain = new Form("StringItem Test"); fmMain.addCommand(cmExit); fmMain.addCommand(cmChange); fmMain.append(siMsg); fmMain.setCommandListener(this); } // Called by application manager to start the MIDlet. public void startApp() { display.setCurrent(fmMain); }

Trang: 17

Cc thnh phn giao din mc cao

public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s) { if (c == cmChange) { // Change label siMsg.setLabel("Section: "); // Change text siMsg.setText("developerWorks"); // Remove the command fmMain.removeCommand(cmChange); } else if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } }

d) TextField
Mt thnh phn TextField th tng t nh bt k cc i tng nhp vn bn tiu biu no. Bn c th ch nh mt nhn, s k t ti a c php nhp, v loi d liu c php nhp. Ngoi ra TextField cn cho php bn nhp vo mt khu vi cc k t nhp vo s c che bi cc k t mt n Phng thc dng ca lp TextField
TextField(String label, String text, int maxSize, int constraints)

Thnh phn th 3 constraints l thnh phn m chng ta quan tm, v n l phng tin xc nh loi d liu no c php nhp vo TextField MIDP nh ngha cc tham s rng buc sau cho thnh phn TextField: ANY: cho php nhp bt k k t no EMAILADDR: ch cho php nhp vo cc a ch email hp l NUMERIC: ch cho php nhp s PHONENUMBER: Ch cho php nhp s in thoi URL: Ch cho php nhp cc k t hp l bn trong URL PASSWORD: che tt c cc k t nhp vo Di y l on m minh ha vic s dng thnh phn TextField
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class TextFieldTest extends MIDlet implements CommandListener

Trang: 18

Cc thnh phn giao din mc cao


{ private Display display; // Reference to Display object private Form fmMain; // Main form private Command cmTest; // Get contents of textfield private Command cmExit; // Command to exit the MIDlet private TextField tfText; // Textfield public TextFieldTest() { display = Display.getDisplay(this); // Create commands cmTest = new Command("Get Contents", Command.SCREEN, 1); cmExit = new Command("Exit", Command.EXIT, 1); // Textfield for phone number tfText = new TextField("Phone:", "", 10, TextField.PHONENUMBER); // Create Form, add Commands and textfield, listen for events fmMain = new Form("Phone Number"); fmMain.addCommand(cmExit); fmMain.addCommand(cmTest); fmMain.append(tfText); fmMain.setCommandListener(this); } // Called by application manager to start the MIDlet. public void startApp() { display.setCurrent(fmMain); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s) { if (c == cmTest) { System.out.println("TextField contains: " + tfText.getString()); } else if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } }

Trang: 19

Cc thnh phn giao din mc cao on m trn ch mi p dng mt rng buc trn i tng TextField. Chng ta c th thm mt rng buc th 2 bng cch:
tfText = new TextField.PASSWORD); TextField("Phone:", "", 10, TextField.PHONENUMBER |

e) ChoiceGroup
Thnh phn ChoiceGroup cho php ngi dng chn t mt danh sch u vo c nh ngha trc. ChoiceGroup c 2 loi: multi-selection(cho php chn nhiu mc): nhm ny c lin quan n cc checkbox exclusive-selection(ch c chn mt mc): nhm ny lin quan n nhm cc radio button Di y l on m minh ha cho vic s dng ChoiceGroup:
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class ChoiceGroupTest extends MIDlet implements ItemStateListener, CommandListener { private Display display; // Reference to display object private Form fmMain; // Main form private Command cmExit; // A Command to exit the MIDlet private Command cmView; // View the choice selected private int selectAllIndex; // Index of the "Select All" option private ChoiceGroup cgPrefs; // Choice Group of preferences private int choiceGroupIndex; // Index of choice group on form public ChoiceGroupTest() { display = Display.getDisplay(this); // Create a multiple choice group cgPrefs = new ChoiceGroup("Preferences", Choice.MULTIPLE); // Append options, with no associated images cgPrefs.append("Replace tabs with spaces", null); cgPrefs.append("Save bookmarks", null); cgPrefs.append("Detect file type", null); selectAllIndex = cgPrefs.append("Select All", null); cmExit = new Command("Exit", Command.EXIT, 1); cmView = new Command("View", Command.SCREEN,2); // Create Form, add components, listen for events fmMain = new Form(""); choiceGroupIndex = fmMain.append(cgPrefs); fmMain.addCommand(cmExit); fmMain.addCommand(cmView);

Trang: 20

Cc thnh phn giao din mc cao


fmMain.setCommandListener(this); fmMain.setItemStateListener(this); } public void startApp() { display.setCurrent(fmMain); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s) { if (c == cmView) { boolean selected[] = new boolean[cgPrefs.size()]; // Fill array indicating whether each element is checked cgPrefs.getSelectedFlags(selected); for (int i = 0; i < cgPrefs.size(); i++) System.out.println(cgPrefs.getString(i) + (selected[i] ? ": selected" : ": not selected")); } else if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } public void itemStateChanged(Item item) { if (item == cgPrefs) { // Is "Select all" option checked ? if (cgPrefs.isSelected(selectAllIndex)) { // Set all checkboxes to true for (int i = 0; i < cgPrefs.size(); i++) cgPrefs.setSelectedIndex(i, true); // Remove the check by "Select All" cgPrefs.setSelectedIndex(selectAllIndex, false); } }

Trang: 21

Cc thnh phn giao din mc cao


} }

f) Spacer
Spacer l thnh phn khng nhn thy, c dng nh v tr cho cc i tng khc trn mn hnh hin th. Bn c th dng Spacer ch r khong trng theo chiu dc v chiu ngang gia cc thnh phn, n gin bng cch ch ra chiu di v chiu rng cho tng ci. V Spacer l thnh phn khng nhn thy nn n khng c s kin b. CustomItem Thnh phn CustomItem cho php bn to ra nhng thnh phn Item ca chnh bn. Nhng thnh phn ny cng ging nh nhng Item khc l cng c th c t vo trong Form v c th nhn bit v x l s kin CustomItem c v ln mn hnh hin th bng phng thc paint(). V th n s ty thuc vo on m c bn hin thc bn trong phng thc paint(). Qu trnh to ra mt i tng CustomItem cng khng khc cc i tng c sn trn nn Java. on m di y minh ha sn ca vic to ra mt i tng CustomItem
public class NewItem extends CustomItem { public NewItem(String label) { super(label); ... } protected void paint(Graphics g, int width, int height) { ... } protected int getMinContentHeight() { ...; } protected int getMinContentWidth() { ... } protected int getPrefContentHeight(int width) { ... }

Trang: 22

Cc thnh phn giao din mc cao


protected int getPrefContentWidth(int height) { ... } ... }

g) Image and ImageItem


Hai lp c dng hin th hnh nh l: Image v ImageItem. Image c dng to ra mt i tng hnh nh v gi thng tin nh l chiu cao v chiu rng, v d nh c bin i hay khng. Lp ImageItem m t mt tm nh s c hin th nh th no, v d tm nh s c t trung tm, hay t v pha bn tri, hay bn trn ca mn hnh MIDP a ra 2 loi hnh nh l loi nh khng bin i v nh bin i. Mt tm nh khng bin i th khng th b thay i k t lc n c to ra. c trng ca loi nh ny l c c t mt tp tin. Mt tm nh bin i v c bn l mt vng nh. iu ny ty thuc vo vic bn to ni dung ca tm nh bng cch ghi n ln vng nh. Chng ta s lm vic vi nhng tm nh khng bin i trong bng sau. Cc phng thc dng cho lp Image v ImageItem
Image createImage(String name) Image createImage(Image source) Image createImage(byte[] imageDate, int imageOffset, int imageLength) Image createImage(int width, int height) Image createImage(Image image, int x, int y, int width, int height, int transform) Image createImage(InputStream stream) Image createRGBImage(int[] rgb, int width, int height, boolean processAlpha) ImageItem(String label, Image img, int layout, String altText)

on m di y m t lm th no to mt tm nh t mt tp tin, v gn n vi mt i tng ImageItem v thm mt bc nh vo mt Form


Form fmMain = new Form("Images"); ... // Create an image Image img = Image.createImage("/house.png"); // Append to a form fmMain.append(new ImageItem(null, img, ImageItem.LAYOUT_CENTER, null));

Ch : PNG l loi nh duy nht c h tr bi bt k thit b MIDP no on m di y m t vic s dng i tng Image v i tng ImageItem
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class ImageTest extends MIDlet implements CommandListener { private Display display; // Reference to Display object private Form fmMain; // The main form

Trang: 23

Cc thnh phn giao din mc cao


private Command cmExit; // Command to exit the MIDlet

public ImageTest() { display = Display.getDisplay(this); cmExit = new Command("Exit", Command.EXIT, 1); fmMain = new Form(""); fmMain.addCommand(cmExit); fmMain.setCommandListener(this); try { // Read the appropriate image based on color support Image im = Image.createImage((display.isColor()) ? "/image_color.png":"/image_bw.png"); fmMain.append(new ImageItem(null, im, ImageItem.LAYOUT_CENTER, null)); display.setCurrent(fmMain); } catch (java.io.IOException e) { System.err.println("Unable to locate or read .png file"); } } public void startApp() { display.setCurrent(fmMain); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command c, Displayable s) { if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } }

Trang: 24

Cc thnh phn giao din mc cao 3. Thnh phn List, Textbox, Alert, v Ticker

Trong phn ny chng ta s xem xt cc i tng ListBox, TextBox, Alert, v Ticker trong cc thnh phn giao din cp cao ca ng dng MIDP. Chng ta hy cng xem li cy phn cp cc thnh phn trnh by trn thit b hon chnh hn

a) List
Mt List cha mt dy cc la chn c th hin mt trong ba dng. Chng ta thy loi cho php nhiu la chn v loi ch c php chn mt khi lm vic vi ChoiceGroup. Dng th 3 l l dng khng tng minh. Cc List khng tng minh uc dng th hin mt thc n cc chn la on m di y minh ha vic s dng mt danh sch khng tng minh
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class ImplicitList extends MIDlet implements CommandListener { private Display display; // Reference to Display object private List lsDocument; // Main list private Command cmExit; // Command to exit public ImplicitList() { display = Display.getDisplay(this); // Create the Commands cmExit = new Command("Exit", Command.EXIT, 1); try

Trang: 25

Cc thnh phn giao din mc cao


{ // Create array of image objects Image images[] = {Image.createImage("/next.png"), Image.createImage("/previous.png"), Image.createImage("/new.png")}; // Create array of corresponding string objects String options[] = {"Next", "Previous", "New"}; // Create list using arrays, add commands, listen for events lsDocument = new List("Document Option:", List.IMPLICIT, options, images); // If you have no images, use this line to create the list // lsDocument = new List("Document Option:", List.IMPLICIT, options, null); lsDocument.addCommand(cmExit); lsDocument.setCommandListener(this); } catch (java.io.IOException e) { System.err.println("Unable to locate or read .png file"); } } public void startApp() { display.setCurrent(lsDocument); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command c, Displayable s) { // If an implicit list generated the event if (c == List.SELECT_COMMAND) { switch (lsDocument.getSelectedIndex()) { case 0: System.out.println("Next selected"); break; case 1: System.out.println("Previous selected"); break;

Trang: 26

Cc thnh phn giao din mc cao

case 2: System.out.println("New selected"); break; } } else if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } }

b) TextBox
TextBox c dng cho php nhp nhiu dng. Thnh phn TextBox v TextField c nhng rng buc ging nhau trong vic ch nh loi ni dung c php nhp vo. V d ANY, EMAIL, URI Di y l phng thc dng ca mt TextBox:
TextBox(String title, String text, int maxSize, int constraints)

Di y l on m minh ha cho vic s dng TextBox:


import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class TextBoxTest extends MIDlet implements CommandListener { private Display display; // Reference to Display object private TextBox tbClip; // Main textbox private Command cmExit; // Command to exit public TextBoxTest() { display = Display.getDisplay(this); // Create the Commands. Notice the priorities assigned cmExit = new Command("Exit", Command.EXIT, 1); tbClip = new TextBox("Textbox Test", "Contents go here..",125, TextField.ANY); tbClip.addCommand(cmExit); tbClip.setCommandListener(this); } public void startApp() { display.setCurrent(tbClip); } public void pauseApp()

Trang: 27

Cc thnh phn giao din mc cao


{ } public void destroyApp(boolean unconditional) { } public void commandAction(Command c, Displayable s) { if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } }

c) Alert v AlertType
Mt Alert n gin l mt hp thoi rt nh. C 2 loi Alert: Modal: l loi hp thoi thng bo c trnh by cho n khi ngi dng n nt ng Non-modal: l loi hp thoi thng bo ch c trnh by trong mt s giy nht nh Cc phng thc dng ca Alert:
Alert(String title) Alert(String title, String alertText, Image alertImage, AlertType alertType)

Thnh phn AlertType s dng m thanh thng bo cho ngi dng bit c mt s kin xy ra. V d bn c th s dng AlertType m mt on m thanh no bo hiu cho ngi dng bit khi c li xy ra Thnh phn AlertType bao gm 5 loi m thanh nh sn l: thng bo, xc nhn, bo li, thng bo v cnh bo Ta thy cc phng thc dng ca Alert cho bit l Alert c th bao gm 1 tham chiu n mt i tng AlertType. Di y l on m minh ha vic s dng Alert v AlertType
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class AlertTest extends MIDlet implements ItemStateListener, CommandListener { private Display display; // Reference to display object private Form fmMain; // Main form private Command cmExit; // Command to exit the MIDlet private ChoiceGroup cgSound; // Choice group public AlertTest() { display = Display.getDisplay(this);

Trang: 28

Cc thnh phn giao din mc cao


// Create an exclusive (radio) choice group cgSound = new ChoiceGroup("Choose a sound", Choice.EXCLUSIVE); // Append options, with no associated images cgSound.append("Info", null); cgSound.append("Confirmation", null); cgSound.append("Warning", null); cgSound.append("Alarm", null); cgSound.append("Error", null); cmExit = new Command("Exit", Command.EXIT, 1); // Create Form, add components, listen for events fmMain = new Form(""); fmMain.append(cgSound); fmMain.addCommand(cmExit); fmMain.setCommandListener(this); fmMain.setItemStateListener(this); } public void startApp() { display.setCurrent(fmMain); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s) { if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } public void itemStateChanged(Item item) { Alert al = null; switch (cgSound.getSelectedIndex()) { case 0: al = new Alert("Alert sound", "Info sound", null, AlertType.INFO); break;

Trang: 29

Cc thnh phn giao din mc cao


case 1: al = new Alert("Alert sound", "Confirmation sound", null, AlertType.INFO); break; case 2: al = new Alert("Alert sound", "Warning sound", null, AlertType.INFO); break; case 3: al = new Alert("Alert sound", "Alarm sound", null, AlertType.INFO); break; case 4: al = new Alert("Alert sound", "Error sound", null, AlertType.INFO); break; } if (al != null) { // Wait for user to acknowledge the alert al.setTimeout(Alert.FOREVER); // Display alert, show main form when done display.setCurrent(al, fmMain); } } }

d) Ticker
Thnh phn Ticker uc dng th hin mt on chui chy theo chiu ngang. Tham s duy nht ca thnh phn Ticker l on vn bn c trnh by. Tc v chiu cun c xc nh bi vic ci t trn thit b no. Phng thc dng ca Ticker
Ticker(String str)

T cy phn cp cc thnh phn th hin trn thit b, ta thy l thnh phn Ticker khng l lp con ca lp Screen m Ticker l mt bin ca lp Screen. iu ny c ngha l mt Ticker c th c gn vo bt c lp con ca lp Screen bao gm c Alert Di y l on m minh ha vic s dng mt Ticker
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class TickerTest extends MIDlet implements CommandListener

Trang: 30

Cc thnh phn giao din mc cao


{ private Display display; // Reference to Display object private List lsProducts; // Products private Ticker tkSale; // Ticker private Command cmExit; // Command to exit the MIDlet public TickerTest() { display = Display.getDisplay(this); cmExit = new Command("Exit", Command.SCREEN, 1); tkSale = new Ticker("Sale: Real Imitation Cuban Cigars...10 for $10"); lsProducts = new List("Products", Choice.IMPLICIT); lsProducts.append("Wicker Chair", null); lsProducts.append("Coffee Table", null); lsProducts.addCommand(cmExit); lsProducts.setCommandListener(this); lsProducts.setTicker(tkSale); } public void startApp() { display.setCurrent(lsProducts); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command c, Displayable s) { if (c == List.SELECT_COMMAND) { switch (lsProducts.getSelectedIndex()) { case 0: System.out.println("Chair selected"); break; case 1: System.out.println("Table selected"); break; } }

Trang: 31

Cc thnh phn giao din mc cao


else if (c == cmExit) { destroyApp(true); notifyDestroyed(); } } }

Trang: 32

Cc thnh phn giao din mc thp

III.Cc thnh phn giao din mc thp ca ng dng MIDP


1. Cc hm API mc thp Mc d cc hm API cp cao cung cp mt tp y cc thnh phn xy dng giao din ng dng ngi dng. Tuy nhin cc thnh phn cp cao khng cung cp phng tin v trc tip ln thit b th hin. V thiu kh nng ny nn cc ng dng c to ra s gp nhiu gii hn. V d hu ht cc nh pht trin game di ng da trn kh nng v cc ng thng v cc hnh dng nh l mt phn tch hp qu trnh pht trin Nu cc hm API cp cao cho php chng ta to ra giao din cho cc ng dng theo chun, th cc hm API cp thp cho php chng ta c th th hin cc tng ca mnh Canvas v Graphics l 2 lp tri tim ca cc hm API cp thp. Bn s lm tt c cc cng vic bng tay. Canvas l mt khung v cho php ngi pht trin c kh nng v ln thit b trnh by cng nh l vic x l s kin. Cn lp Graphics cung cp cc cng c tht s v nh drawRoundRect() v drawString() 2. Lp Canvas Lp Canvas cung cp mt khung v cho php to ra giao din ty bin ngi dng. Mt s lng ln cc phng thc trong lp ny c dng x l s kin, v nh v chui ln thit b hin th. Trong phn ny s bao gm cc mc H thng ta To i tng Canvas V ln trn i tng Canvas X l cc s kin hnh ng X l cc s kin phm nhn X l s kin hnh ng ca Game X l s kin con tr Chng ta s to ra 2 ng dng MIDlet minh ha kh nng ca lp Canvas. ng dng u tin l KeyMapping s minh ha lm th no chp, nhn ra v x l m phm nhn v cc s kin c lin quan n Game. ng dng cn li l ScratchPad s minh ha lm th no thao tc cc s kin con tr to ra mt chng trnh v ng thng n gin

a) H thng trc ta
Mc tiu u tin ca chng ta l lm quen vi h thng trc ta lm vic vi thit b th hin. H thng ta cho lp Canvas c tm ta l im tri trn ca thit b trnh by. Gi tr x tng dn v pha phi, gi tr y tng dn khi i xung pha di. Khi v dy bt v l mt im nh

Trang: 33

Cc thnh phn giao din mc thp

Cc phng thc sau y s gip xc nh chiu rng v chiu cao ca canvas:


int getWidth(): xc nh chiu rng ca canvas int getHeight (): xc nh chiu cao ca canvas

Chiu rng v chiu cao ca Canvas cng i din cho ton b din tch khung v c th trn thit b trnh by. Ni cch khc, bn khng th ch nh kch thc cho canvas, m phn mm trn mt thit b MIDP s tr v din tch ln nht c th c i vi mt thit b cho trc

b) To mt i tng Canvas
Bc u tin lm vic vi mt lp Canvas l to ra mt lp tha k t lp Canvas
class TestCanvas extends Canvas implements CommandListener { private Command cmdExit; ... display = Display.getDisplay(this); cmdExit = new Command("Exit", Command.EXIT, 1); addCommand(cmdExit); setCommandListener(this); ... protected void paint(Graphics g) { // Draw onto the canvas ... } } TestCanvas canvas = new TestCanvas(this);

Trang: 34

Cc thnh phn giao din mc thp

c) V trn i tng Canvas


Phng thc paint ca lp Canvas cho php bn v cc hnh dng, v nh, xut chui. on m sau minh ha vic xa mn hnh th hin bng mt mu trng
protected void paint(Graphics g) { // Set background color to white g.setColor(255, 255, 255); // Fill the entire canvas g.fillRect(0, 0, getWidth(), getHeight()); }

Chng ta c th s dng mt tham chiu n mt i tung Graphics bn trong thn phng thc paint() thc hin cng vic v thc s

d) S kin hnh ng
Cng nh cc thnh phn Form, List, v TextBox, mt Canvas c th x l cc s Command. Chng ta c th x l cc s kin Command trn thnh phn Canvas cung cch nh cc thnh phn khc on m sau minh ha vic x l s kin Command trn thnh phn Canvas
class TestCanvas extends Canvas implements CommandListener { private Command cmdExit; ... display = Display.getDisplay(this); cmdExit = new Command("Exit", Command.EXIT, 1); addCommand(cmdExit); setCommandListener(this); ... protected void paint(Graphics g) { // Draw onto the canvas ... } public void commandAction(Command c, Displayable d) { if (c == cmdExit) ... } }

Trang: 35

Cc thnh phn giao din mc thp

e) M phm
Trong trng hp x l cc hnh ng ca cc phm mm, mt Canvas c th truy cp n 12 m phm. Nhng m ny c m bo lun lun c trn bt k cc thit b MIDP no
KEY_NUM0 KEY_NUM1 KEY_NUM2 KEY_NUM3 KEY_NUM4 KEY_NUM5 KEY_NUM6 KEY_NUM7 KEY_NUM8 KEY_NUM9 KEY_STAR KEY_POUND

Nm phng thc x l cc m phm l:


void keyPressed(int keyCode) void keyReleased(int keyCode) void keyRepeated(int keyCode) boolean hasRepeatEvents() String getKeyName(int keyCode)

f) Cc hnh ng trong x l cc tr chi


MIDP thng c s dng to cc tr chi trn nn Java. Cc hng s sau c nh ngha x l cc s kin c lin quan n tr chi trong MIDP
UP DOWN LEFT RIGHT FIRE GAME_A GAME_B GAME_C GAME_D

Ni mt cch n gin th cc gi tr ny c nh x thnh cc phm mi tn ch hng ca thit b, nhng khng phi tt c cc thit b di ng u c nhng gi tr ny. Nu mt thit b di ng thiu cc phm mi tn th cc hnh ng ca tr chi s c nh x vo cc nt bm, v d phm tri c nh x vo phm s 2, phm phi c nh x vo phm s 5, v c tip tc nh th. Hnh di y cho thy cc hnh ng ca tr chi s c nh x ln mt thit b di ng da trn kh nng ca cc phm ch hng

Trang: 36

Cc thnh phn giao din mc thp

g) Xc nh cc hnh ng ca tr chi
on m sau y m t mt cch xc nh cc hnh ng ca tr chi t gi cc phng thc thch hp da trn cc hnh ng xy ra
protected void keyPressed(int keyCode) { switch (getGameAction(keyCode)) { case Canvas.FIRE: shoot(); break; case Canvas.RIGHT: goRight(); break; ... } }

Mt la chn na l c th to mt tham chiu cho mi hnh ng ca tr chi thng qua qu trnh khi to gi tr cho cc bin
// Initialization keyFire = getKeyCode(FIRE); keyRight = getKeyCode(RIGHT); keyLeft = getKeyCode(LEFT); ...

Trang: 37

Cc thnh phn giao din mc thp

// Runtime protected void keyPressed(int keyCode) { if (keyCode == keyFire) shoot(); else if (keyCode == keyRight) goRight() ... }

on m di y minh ha mt s chc nng ca Canvas v cch x l phm


import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class KeyMapping extends MIDlet { private Display display; // The display private KeyCodeCanvas canvas; // Canvas public KeyMapping() { display = Display.getDisplay(this); canvas = new KeyCodeCanvas(this); } protected void startApp() { display.setCurrent( canvas ); } protected void pauseApp() {} protected void destroyApp( boolean unconditional ) {} public void exitMIDlet() { destroyApp(true); notifyDestroyed(); } } /*-------------------------------------------------* Class KeyCodeCanvas *-------------------------------------------------*/ class KeyCodeCanvas extends Canvas implements CommandListener { private Command cmExit; // Exit midlet private String keyText = null; // Key code text private KeyCodes midlet;

Trang: 38

Cc thnh phn giao din mc thp

/*-------------------------------------------------* Constructor *-------------------------------------------------*/ public KeyCodeCanvas(KeyCodes midlet) { this.midlet = midlet; // Create exit command and listen for events cmExit = new Command("Exit", Command.EXIT, 1); addCommand(cmExit); setCommandListener(this); } /*-------------------------------------------------* Paint the text representing the key code *-------------------------------------------------*/ protected void paint(Graphics g) { // Clear the background (to white) g.setColor(255, 255, 255); g.fillRect(0, 0, getWidth(), getHeight()); // Set color and draw text if (keyText != null) { // Draw with black pen g.setColor(0, 0, 0); // Center text g.drawString(keyText, getWidth()/2, getHeight()/2, Graphics.TOP | Graphics.HCENTER); } } /*-------------------------------------------------* Command event handling *-------------------------------------------------*/ public void commandAction(Command c, Displayable d) { if (c == cmExit) midlet.exitMIDlet(); } /*-------------------------------------------------* Key code event handling *-------------------------------------------------*/ protected void keyPressed(int keyCode) { keyText = getKeyName(keyCode); repaint();

Trang: 39

Cc thnh phn giao din mc thp


} }

h) S kin con tr
Trong phn ny chng ta s qun l s kin con tr trong mt Canvas. Nhng s kin ny c thit k lm thun tin cho vic tng tc vi cc thit b c dng con tr. Mt s phng thc c cung cp nhm h tr cho vic x l s kin con tr:
boolean hasPointerEvents() boolean hasPointerMotionEvents() void pointerPressed(int x, int y) void pointerReleased(int x, int y) void pointerDragged(int x, int y)

Cc phng thc trn c th t gii thch chc nng thng qua tn ca chnh mnh. Phng thc hasPointerMotionEvents() tr v mt gi tr c kiu boolean nhm ch r rng thit b di ng c h tr khi nim nhp chut v r hay khng on chng trnh di y minh ha vic s dng cc s kin con tr thc hin mt chng trnh v n gin
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class ScratchPad extends MIDlet { private Display display; // Display object private ScratchPadCanvas canvas; // Canvas public ScratchPad() { display = Display.getDisplay(this); canvas = new ScratchPadCanvas(this); } protected void startApp() { display.setCurrent( canvas ); } protected void pauseApp() {} protected void destroyApp( boolean unconditional ) {} public void exitMIDlet() { destroyApp(true); notifyDestroyed(); } }

Trang: 40

Cc thnh phn giao din mc thp

/*-------------------------------------------------* Class ScratchPadCanvas * * Pointer event handling *-------------------------------------------------*/ class ScratchPadCanvas extends Canvas implements CommandListener { private Command cmExit; // Exit midlet private Command cmClear; // Clear display private int startx = 0, // Where pointer was clicked starty = 0, currentx = 0, // Current location currenty = 0; private ScratchPad midlet; private boolean clearDisplay = true; /*-------------------------------------------------* Constructor *-------------------------------------------------*/ public ScratchPadCanvas(ScratchPad midlet) { this.midlet = midlet; // Create exit command and listen for events cmExit = new Command("Exit", Command.EXIT, 1); cmClear = new Command("Clear", Command.SCREEN, 1); addCommand(cmExit); addCommand(cmClear); setCommandListener(this); } /*-------------------------------------------------* Draw line based on start and ending points *-------------------------------------------------*/ protected void paint(Graphics g) { // Clear the background (to white) if (clearDisplay) { g.setColor(255, 255, 255); g.fillRect(0, 0, getWidth(), getHeight()); clearDisplay = false; startx = currentx = starty = currenty = 0; return; } // Draw with black pen g.setColor(0, 0, 0);

Trang: 41

Cc thnh phn giao din mc thp

// Draw line g.drawLine(startx, starty, currentx, currenty); // New starting point is the current position startx = currentx; starty = currenty; } /*-------------------------------------------------* Command event handling *-------------------------------------------------*/ public void commandAction(Command c, Displayable d) { if (c == cmExit) midlet.exitMIDlet(); else if (c == cmClear) { clearDisplay = true; repaint(); } } /*-------------------------------------------------* Pointer pressed *-------------------------------------------------*/ protected void pointerPressed(int x, int y) { startx = x; starty = y; } /*-------------------------------------------------* Pointer moved *-------------------------------------------------*/ protected void pointerDragged(int x, int y) { currentx = x; currenty = y; repaint(); } }

3. Lp Graphics Chng ta s dng i tng Graphics v ln mt Canvas.

a) H tr mu
Mt ng dng MIDP ch c mt i tng Display. i tng ny uc dng ly thng tin ca mn hnh hin th hin ti, v d nh s mu h tr v cc phng Trang: 42

Cc thnh phn giao din mc thp thc yu cu cc i tng c hin th. i tng Display n gin l mt b qun l s hin th ca thit b v iu khin nhng g s c hin th ra trn thit b. boolean isColor() int numColors() Phng thc u tin cho bit thit b c h tr hin th mu hay khng. Nu c th phng thc th 2 s c gi xc nh s mu c h tr. Cc phng thc tip theo di y ly v mu v thit lp mu a thch ca bn.
void setColor(int RGB) void setColor(int red, int green, int blue) int getColor() int getBlueComponent() int getGreenComponent() int getRedComponent() void setGrayScale(int value) int getGrayScale()

Ch bn c th xc nh mu bng 2 cch. Cch 1: bn c th xc nh mt s nguyn i din cho 3 gi tr ca mu l , xanh l cy v xanh dng vi 8 bit cho mi mu. Hay cch 2 l bn c th dng tng tham s ring bit xc nh mi mu. Khi s dng mt gi tr lu gi mu, th mu s chim 8 bit u k t bn tri, tip theo l 8 bit dnh cho mu xanh l cy, sau cng l mu xanh dng. Di y s hng dn bn cch thit lp mu ch s dng mt s nguyn:
int red = 0, green = 128, blue = 255; ... g.setColor((red << 16) | (green << 8) | blue);

V bn c th xc nh mu bng cch thit lp gi tr cho 3 tham s:


g.setColor(red, green, blue);

b) Loi nt v
Bn c th chn nt khi v ng thng, cung v hnh ch nht trn thit b hin th. Di y l cc phng thc dng thit lp loi nt v
int getStrokeStyle() void setStrokeStyle(int style)

Hai kiu nt v c nh ngha trong lp Graphics l nt chm, v nt lin


g.setStrokeStyle(Graphics.DOTTED); hay g.setStrokeStyle(Graphics.SOLID);

c) V cung
Khi v mt cung, bn c th v n ch c ng bao xung quanh hay yu cu n c t bn trong. Bn c th bt u bng cch ch nh chiu bao quanh bn ngoi ca mt hnh hp ch nht tng tng. Gc bt u xc nh v tr bt u v khung, vi gi tr 0 c xc nh ti thi im 3 gi. Gi tr dng tnh theo ngc Trang: 43

Cc thnh phn giao din mc thp chiu kim ng h. Gc ca cung ch ra rng c bao nhiu c v tnh t gc ban u, i theo ngc chiu kim ng h. hiu r nhng phn ny chng ta hy cng xem1 v d sau:
g.drawArc(10, 10, 100, 100, 0, 150);

on m trn yu cu v mt cung, cung ny c bao bi mt hnh ch nht c ta im tri trn l (10, 10), chiu rng v chiu di l 100, gc bt u l 0, gc kt thc l 150

Mt s cc phng thc dng v cung void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) Di y l on m minh ha vic s dng cc hm trn v mt cung
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class DrawShapes extends MIDlet { private Display display; // The display private ShapesCanvas canvas; // Canvas public DrawShapes() { display = Display.getDisplay(this); canvas = new ShapesCanvas(this); } protected void startApp() { display.setCurrent( canvas ); } protected void pauseApp()

Trang: 44

Cc thnh phn giao din mc thp


{} protected void destroyApp( boolean unconditional ) {} public void exitMIDlet() { destroyApp(true); notifyDestroyed(); } } /*-------------------------------------------------* Class ShapesCanvas * * Draw arcs *-------------------------------------------------*/ class ShapesCanvas extends Canvas implements CommandListener { private Command cmExit; // Exit midlet private DrawShapes midlet; public ShapesCanvas(DrawShapes midlet) { this.midlet = midlet; // Create exit command and listen for events cmExit = new Command("Exit", Command.EXIT, 1); addCommand(cmExit); setCommandListener(this); } /*-------------------------------------------------* Draw shapes *-------------------------------------------------*/ protected void paint(Graphics g) { // Clear background to white g.setColor(255, 255, 255); g.fillRect(0, 0, getWidth(), getHeight()); // Black pen g.setColor(0, 0, 0); // Start at 3 o'clock and rotate 150 degrees g.drawArc(10, 10, 100, 100, 0, 150); // // Fill the arc g.fillArc(10, 10, 100, 100, 0, 150); // Start at 12 o'clock and rotate 150 degrees

Trang: 45

Cc thnh phn giao din mc thp


// g.drawArc(10, 10, 100, 100, 90, 150);

// Change the size of the bounding box // Start at 12 o'clock and rotate 150 degrees // g.drawArc(15, 45, 30, 70, 90, 150); } public void commandAction(Command c, Displayable d) { if (c == cmExit) midlet.exitMIDlet(); } }

d) V hnh ch nht
Cng ging nh cung th hnh ch nht c th ch c v vin bao quanh hoc t bn trong. Bn cnh bn c th v hnh ch nht c 4 gc l trn hoc l vung. Di y l mt s phng thc v hnh ch nht:
void drawRect(int x, int y, int width, int height) void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) void fillRect(int x, int y, int width, int height) void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)

Khi v hnh ch nht c 4 gc l trn th bn phi xc nh ng knh theo chiu ngang(arcWidth) v ng knh theo chiu dc(arcHeight). Nhng tham s ny c nh ngha sc nt ca cung theo mi chiu. Gi tr cng ln th hin mt cung tng dn, ngc li l mt ng cong hp

e) Font ch
Phn sau y cng quan trng khng km l cch s dng font ch c h tr bi giao din cp thp ca ng dng MIDP. Sau y l mt s cc phng thc dng ca lp Font
Font getFont(int face, int style, int size) Font getFont(int fontSpecifier) Font getDefaultFont()

Mt s thuc tnh ca lp Font


FACE_SYSTEM FACE_MONOSPACE FACE_PROPORTIONAL STYLE_PLAIN STYLE_BOLD STYLE_ITALIC STYLE_UNDERLINED SIZE_SMALL SIZE_MEDIUM SIZE_LARGE

Cc tham s kiu dng c th c kt hp thng qua ton t hay. V d Trang: 46

Cc thnh phn giao din mc thp


Font font = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD | Font.STYLE_ITALIC, Font.SIZE_MEDIUM);

Sau khi bn c mt tham chiu n mt i tng Font, bn c th truy vn n xc nh thng tin ca cc thuc tich ca n.
int getFace() int getStyle() int getSize() boolean isPlain() boolean isBold() boolean isItalic() boolean isUnderlined()

Kch thc ca cc font ch c xc nh bi chiu cao ca font ch, b di tnh bng im nh ca mt chui k t trong mt font xc nh. Mt s cc phng thc sau h tr khi tng tc vi mt i tng font
int getHeight() int getBaselinePosition() int charWidth(char ch) int charsWidth(char[] ch, int offset, int length) int stringWidth(String str) int substringWidth(String str, int offset, int length)

f) im neo
xc nh ta x, y ca chui k t c hin th, th im neo cho php bn ch ra v tr mun t ta x, y trn hnh ch nht bao quanh chui k t

C 6 im neo c nh ngha trc, 3 theo chiu dc v 3 theo chiu thng ng, Khi xc nh im neo v chui (cc im neo thng c s dng thnh tng cp), bn phi chn mt im honh v mt im tung . Cc im neo c nh ngha nh di y
Chiu ngang LEFT (Bn tri) HCENTER (Chnh gia ca chiu ngang) RIGHT (Bn phi) Chiu dc TOP ( trn) BASELINE (ng thng c s) BOTTOM ( di)

Trang: 47

Cc thnh phn giao din mc thp Khi s dng im neo th bn cn phi ch ra ta x, y ca hnh ch nht bao quanh. V d
g.drawString("developerWorks", 0, 0 , Graphics.TOP | Graphics.LEFT);

Hnh di y m t kt qu ca hm trn

Bng cch thay i im neo, chng ta c th thay i v tr hin th ca chui k t trn thit b di ng. V d tip theo chng ta s minh ha tip khi thay i im neo th v tr ca chui k t cng thay i theo:
g.drawString("developerWorks", 0, 0 , Graphics.TOP | Graphics.HCENTER);

g) V cc chui k t
Sau khi tm hiu v font v cc im neo, bn c th v chui k t ra mn hnh thng qua mt s cc phng thc sau:
void drawChar(char character, int x, int y, int anchor) void drawChars(char[] data, int offset, int length, int x, int y, int anchor) void drawString(String str, int x, int y, int anchor) void drawSubstring(String str, int offset, int len, int x, int y, int anchor)

V d:
protected void paint(Graphics g) { // Get center of display int xcenter = getWidth() / 2, ycenter = getHeight() / 2;

Trang: 48

Cc thnh phn giao din mc thp

// Choose a font g.setFont(Font.getFont(Font.FACE_SYSTEM, Font.STYLE_ITALICS, Font.SIZE_MEDIUM)); // Specify the center of the text (bounding box) using the anchor point g.drawString("developerWorks", xcenter, ycenter, Graphics.BASELINE | Graphics.HCENTER); }

Tip theo l v d minh ha vic s dung font v xut chui ra thit b hin th
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class FontViewer extends MIDlet { protected Display display; // The display protected PrefsForm fmPrefs; // Form to choose font prefs protected FontCanvas cvFont; // Canvas to display text (in preferred font) public FontViewer() { display = Display.getDisplay(this); cvFont = new FontCanvas(this); fmPrefs = new PrefsForm("Preferences", this); } protected void startApp() { showCanvas(); } protected void showCanvas() { display.setCurrent(cvFont); } protected void pauseApp() {} protected void destroyApp( boolean unconditional ) {} public void exitMIDlet() { destroyApp(true); notifyDestroyed(); } } /*-------------------------------------------------* FontCanvas.java

Trang: 49

Cc thnh phn giao din mc thp


* * Draw text using specified Font *-------------------------------------------------*/ import javax.microedition.lcdui.*; class FontCanvas extends Canvas implements CommandListener { private int face, // Font face style, // style size; // size private String text = "developerWorks"; // Text to display in preferred font private Command cmExit; // Exit midlet private Command cmPrefs; // Call the preferences form private FontViewer midlet; // Reference to the main midlet public FontCanvas(FontViewer midlet) { this.midlet = midlet; // Create commands and listen for events cmExit = new Command("Exit", Command.EXIT, 1); cmPrefs = new Command("Prefs", Command.SCREEN, 2); addCommand(cmExit); addCommand(cmPrefs); setCommandListener(this); } /*-------------------------------------------------* Draw text *-------------------------------------------------*/ protected void paint(Graphics g) { // Clear the display g.setColor(255, 255, 255); // White pen g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(0, 0, 0); // Black pen // Use the user selected font preferences g.setFont(Font.getFont(face, style, size)); // Draw text at center of display g.drawString(text, getWidth() / 2, getHeight() / 2, Graphics.BASELINE | Graphics.HCENTER); } protected void setFace(int face) { this.face = face; } protected void setStyle(int style)

Trang: 50

Cc thnh phn giao din mc thp


{ this.style = style; } protected void setSize(int size) { this.size = size; } public void setText(String text) { this.text = text; } public int getFace() { return face; } public int getStyle() { return style; } public int getSize() { return size; } public void commandAction(Command c, Displayable d) { if (c == cmExit) midlet.exitMIDlet(); else if (c == cmPrefs) midlet.display.setCurrent(midlet.fmPrefs); } } /*-------------------------------------------------* PrefsForm.java * * Form that allows user to select font preferences *-------------------------------------------------*/ import javax.microedition.lcdui.*; public class PrefsForm extends Form implements CommandListener, ItemStateListener { private FontViewer midlet; // Main midlet private Command cmBack, // Back to canvas cmSave; // Save new font prefs

Trang: 51

Cc thnh phn giao din mc thp


protected ChoiceGroup cgFace, // Font face cgStyle, // style cgSize; // size protected TextField tfText; // Text string to display on canvas // (with the requested font prefs) private int face = 0, // Values for font attributes style = 0, // that are obtained from the choicegroups size = 0; private String text = null; // Value for text string from the textfield public PrefsForm(String title, FontViewer midlet) { // Call the form constructor super(title); // Save reference to MIDlet so we can // access the display manager class this.midlet = midlet; // Commands cmSave = new Command("Save", Command.SCREEN, 1); cmBack = new Command("Back", Command.BACK, 2); // Exclusive choice group for font face cgFace = new ChoiceGroup("Face Options", Choice.EXCLUSIVE); cgFace.append("System", null); cgFace.append("Monospace", null); cgFace.append("Proportional", null); // Multiple choice group for font style cgStyle = new ChoiceGroup("Style Options", Choice.MULTIPLE); cgStyle.append("Plain", null); cgStyle.append("Bold", null); cgStyle.append("Italic", null); cgStyle.append("Underlined", null); // Exclusive choice group for font size cgSize = new ChoiceGroup("Size Options", Choice.EXCLUSIVE); cgSize.append("Small", null); cgSize.append("Medium", null); cgSize.append("Large", null); // Textfield for text to display on canvas tfText = new TextField("", "developerWorks", 20, TextField.ANY); // Create form contents and listen for events append(cgFace); append(cgStyle); append(cgSize); append(tfText); addCommand(cmSave);

Trang: 52

Cc thnh phn giao din mc thp


addCommand(cmBack); setCommandListener(this); setItemStateListener(this); } /*-------------------------------------------------* Command event handling *-------------------------------------------------*/ public void commandAction(Command c, Displayable s) { if (c == cmSave) { // Set the values in canvas class to those selected here midlet.cvFont.setFace(face); midlet.cvFont.setStyle(style); midlet.cvFont.setSize(size); // Make sure we aren't passing a null value midlet.cvFont.setText(tfText.getString() != null ? tfText.getString() : "developerWorks"); } // No specific check needed for "Back" command // Always return to the canvas at this point midlet.showCanvas(); } public void itemStateChanged(Item item) { if (item == cgFace) { switch (cgFace.getSelectedIndex()) { case 0: face = Font.FACE_SYSTEM; break; case 1: face = Font.FACE_MONOSPACE; break; case 2: face = Font.FACE_PROPORTIONAL; break; } } else if (item == cgStyle) { boolean[] b = new boolean[4]; cgStyle.getSelectedFlags(b); style = 0;

Trang: 53

Cc thnh phn giao din mc thp


// STYLE_PLAIN has a value of 0 // No need to check for b[0] // If bold selected if (b[1]) style = Font.STYLE_BOLD; // If italic selected if (b[2]) style |= Font.STYLE_ITALIC; // If underlined selected if (b[3]) style |= Font.STYLE_UNDERLINED; } else if (item == cgSize) { switch (cgSize.getSelectedIndex()) { case 0: size = Font.SIZE_SMALL; break; case 1: size = Font.SIZE_MEDIUM; break; case 2: size = Font.SIZE_LARGE; break; } } else if (item == tfText) { text = tfText.getString(); } } }

h) V nh
Lp Graphics cung cp 1 phng thc dng v nh:
drawImage(Image img, int x, int y, int anchor)

Chng ta cng p dng tng bc khi v nh cng ging nh khi xut chui ra mn hnh. i vi c 2 th chng ta u phi bt u bng vic thit lp ta x, y cng nh im neo. Danh sch cc im neo cho vic hin th nh cng khng khc my so vi vic xut chui, tuy nhin khng ging vi vic xut chui th mt bc nh c mt im trung tm. V th VCENTER c thay th cho gia tr BASELINE khi lm vic vi nh
Chiu ngang LEFT (Bn tri)

Trang: 54

Cc thnh phn giao din mc thp


HCENTER (im chnh gia theo chiu ngang) RIGHT (Bn phi) Chiu dc TOP (im trn) VCENTER (im chnh gia theo chiu dc) BOTTOM (Bn di

Trong cc phn trc, chng ta to ra cc ng dng MIDP cho vic trnh by mt tm nh c t mt ngun ti nguyn l mt tp tin. Loi nh ny khng cho php thay i, v v vy cn c bit vi tn l nh khng th thay i. i vi v d sau y, chng ta s to ra mt tm nh t nhng ng tp nham, chng ta s cp pht b nh cho tm nh, ly tham chiu n mt i tng Graphics, v chng ta s t v ni dung tm nh. Loi nh ny cn c bit vi mt ci tn l nh c th bin thay i c
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class DrawImage extends MIDlet { private Display display; // The display private ImageCanvas canvas; // Canvas public DrawImage() { display = Display.getDisplay(this); canvas = new ImageCanvas(this); } protected void startApp() { display.setCurrent( canvas ); } protected void pauseApp() {} protected void destroyApp( boolean unconditional ) {} public void exitMIDlet()

Trang: 55

Cc thnh phn giao din mc thp


{ destroyApp(true); notifyDestroyed(); } } /*-------------------------------------------------* Class ImageCanvas * * Draw mutable image *-------------------------------------------------*/ class ImageCanvas extends Canvas implements CommandListener { private Command cmExit; // Exit midlet private DrawImage midlet; private Image im = null; private String message = "developerWorks"; public ImageCanvas(DrawImage midlet) { this.midlet = midlet; // Create exit command and listen for events cmExit = new Command("Exit", Command.EXIT, 1); addCommand(cmExit); setCommandListener(this); try { // Create mutable image im = Image.createImage(100, 20); // Get graphics object to draw onto the image Graphics graphics = im.getGraphics(); // Specify a font face, style and size Font font = Font.getFont(Font.FACE_SYSTEM, Font.SIZE_MEDIUM); graphics.setFont(font); Font.STYLE_PLAIN,

// Draw a filled (blue) rectangle, with rounded corners graphics.setColor(0, 0, 255); graphics.fillRoundRect(0,0, im.getWidth()-1, im.getHeight()-1, 20, 20); // Center text horizontally in the image. Draw text in white graphics.setColor(255, 255, 255); graphics.drawString(message, (im.getWidth() / 2) - (font.stringWidth(message) / 2), (im.getHeight() / 2) - (font.getHeight() / 2), Graphics.TOP | Graphics.LEFT);

Trang: 56

Cc thnh phn giao din mc thp


} catch (Exception e) { System.err.println("Error during image creation"); } } /*-------------------------------------------------* Draw mutable image *-------------------------------------------------*/ protected void paint(Graphics g) { // Clear the display g.setColor(255, 255, 255); g.fillRect(0, 0, getWidth(), getHeight()); // Center the image on the display if (im != null) g.drawImage(im, getWidth() / 2, getHeight() / 2, Graphics.VCENTER | Graphics.HCENTER); } public void commandAction(Command c, Displayable d) { if (c == cmExit) midlet.exitMIDlet(); } }

i) Mt s cc phng thc khc ca lp Graphics


clip() v translate() l 2 phng thc ca lp Graphics. Mt vng hin th c ct xn c nh ngha l khu vc hin th ca thit b di ng, vng ny s c cp nht trong sut thao tc v li. Di y l mt s phng thc h tr cho vic xn mt vng hin th
void setClip(int x, int y, int width, int height) void clipRect(int x, int y, int width, int height) int getClipX() int getClipY() int getClipWidth() int getClipHeight()

translate() l mt phng thc c s dng c lin quan n h thng trc ta . Chng ta c th tnh tin h trc ta n mt im x, y khc. Mt s phng thc h tr cho vic tnh tin h trc ta
void translate(int x, int y) int getTranslateX() int getTranslateY()

Trang: 57

Cc thnh phn giao din mc thp 4. Cc hm API dng lp trnh Game

Cc hm API dnh lp trnh Game c gii thiu trong bn MIDP 2.0, nhng hm ny l phng tin pht trin game vi nhiu phn ha. Cc hm API dnh cho Game l mt phn ca gi javax.microedition.lcdui.game Lp GameCanvas gn nh ging lp Canvas, GameCanvas cung cp nn tng to giao din ngi dng, nhng trong trng hp ny ch cho vic to games. GameCanvas cha mt vng nh tch ri vi vng nh mn hnh cho mi th hin v cung cp cc phng tin tch hp xc nh tnh trng cc phm tr chi. Di y l lp GameCanvas:
public abstract class GameCanvas extends Canvas

Layer l mt lp tru tng c s dng th hin mt i tng trc quan trong mt tr chi. Sprite l mt lp con ca lp Layer, lp ny c cung cp th hin cho mt bc nh. Ngoi ra Sprite cn c th bao gm mt dy cc khung nh. thc hin kh nng chuyn ng, cc khung nh c th hin theo mt th t to hiu ng di chuyn nh. Cc php bin i nh l php quay v php lt nh c th c p dng i vi mt i tng Sprite. Di y l m t cho 2 lp Layer v Sprite
public abstract class Layer extends Object public class Sprite extends Layer

TiledLayer l mt lp tng t nh mt bng tnh, vi mi i din cho mt tm nh. Mt TiledLayer n gin c dng th hin cc phn t trc quan c kch thc ln, nh l nn ca mt tr chi.
public class TiledLayer extends Layer

n gin x l cho vic v nhiu lp trong mt tr chi, cc hm API dnh cho vic lp trnh tr chi li c th lp LayoutManager. Lp LayoutManager ny cha mt danh sch c th t cc i tng Layers v xc nh khu vc no cn c v li v th hin theo ng trt t. Lp LayoutManager c th hin nh di y:
public class LayerManager extends Object

Trang: 58

Cc thnh phn giao din mc thp

IV.

X l s kin
1. i tng Command

Khi mt i tng xy ra trn thit b di ng, mt i tng Command gi thng tin v s kin . Thng tin ny bao gm loi hnh ng thc thi, nhn ca mnh lnh v u tin ca chnh n. Trong J2ME, cc hnh ng ni chung c th hin di dng cc nt trn thit b Nu c qu nhiu hnh ng c hin th trn thit b, thit b s to ra mt thc n cha cc hnh ng Ch c cc thnh phn MIDP sau y mi c th cha cc i tng Command l: Form, TextBox, List v Canvas. Cc bc c bn x l cc s kin vi mt i tng Command: To mt i tng Command t i tng Command ln trn mt i tng Form, TextBox, List, hay Canvas To mt b lng nghe Khi c mt s kin xy ra, b lng nghe s pht sinh mt li gi n phng thc commandAction(). Trong thn phng thc ny bn c th xc nh i tng no pht sinh ra s kin v to ra cc x l tng ng Di y l on m minh ha vic to ra s kin Command v x l s kin:
private Form fmMain; // Form private Command cmExit; // Command to exit the MIDlet ... fmMain = new Form("Core J2ME"); // Create Form and give it a title // Create Command object, with label, type and priority cmExit = new Command("Exit", Command.EXIT, 1); ... fmMain.addCommand(cmExit); // Add Command to Form fmMain.setCommandListener(this); // Listen for Form events ... public void commandAction(Command c, Displayable s) { if (c == cmExit) { destroyApp(true); notifyDestroyed(); } }

Trang: 59

Cc thnh phn giao din mc thp

2. i tng Item

Ngoi vic x l s kin bng i tng Command ta c th x l s kin bng i tng Item. Nhiu i tng trong MIDP c nh ngha trc cho vic x l cc s kin c th no . V d i tng DateField cho php ngi s dng chn la ngy v gi trn mn hnh, i tng TextField cho php ngi dng nhp vo mt chui cc k t, s v cc k t c bit Tng t nh vic x l s kin bng i tng Command, th khi c mt thay i xy ra i vi bt k thnh phn Item no th phng thc itemStateChanged() s c gi. V chng ta s thc hin cc x l bn trong phng thc ny Di y l on m minh ha vic to ra s kin Command v x l s kin:
private Form fmMain; // Form private DateField dfToday; // DateField item ... fmMain = new Form("Core J2ME"); // Create Form object dfToday = new DateField("Today:", DateField.DATE); // Create DateField ... fmMain.append(dfToday); // Add DateField to Form fmMain.setItemStateListener(this); // Listen for Form events ... public void itemStateChanged(Item item) { // If the datefield initiated this event if (item == dfToday) ... }

3. V d

Di y l on m minh ha vic to ra v x l cc s kin Command, Item


import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class EventProcessing extends MIDlet implements ItemStateListener, CommandListener { private Display display; // Reference to Display object for this MIDlet private Form fmMain; // Main Form private Command cmExit; // Command to exit the MIDlet private TextField tfText; // TextField component (item)

Trang: 60

Cc thnh phn giao din mc thp

public EventProcessing() { display = Display.getDisplay(this); // Create the date and populate with current date tfText = new TextField("First Name:", "", 10, TextField.ANY); cmExit = new Command("Exit", Command.EXIT, 1); // Create the Form, add Command and DateField // listen for events from Command and DateField fmMain = new Form("Event Processing Example"); fmMain.addCommand(cmExit); fmMain.append(tfText); fmMain.setCommandListener(this); // Capture Command events (cmExit) fmMain.setItemStateListener(this); // Capture Item events (dfDate) } // Called by application manager to start the MIDlet. public void startApp() { display.setCurrent(fmMain); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s) { System.out.println("Inside commandAction()"); if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } public void itemStateChanged(Item item) { System.out.println("Inside itemStateChanged()"); } }

Trang: 61

Record Management System

V. Record Management System


MIDP khng s dng h thng file lu tr d liu. Thay vo MIDP lu ton b thng tin vo non-volatile memory bng h thng lu tr gi l Record Management System (RMS). 1. Persistent Storage Through the Record Store RMS l h thng c t chc v qun l di dng cc record (bn ghi). Mi bn ghi (sau ny gi l Record) c th cha bt k loi d liu no, chng c th l kiu s nguyn, chui k t hay c th l mt nh v kt qu l mt Record l mt chui (mng) cc byte. Nu bn m ho d liu ca bn di dng nh phn (binary), bn c th lu tr d liu bng Record sau c d liu t Record v khi phc li d liu ban u. Tt nhin kch thc d liu ca bn khng c vut qu gii hn qui nh ca thit b di ng. RMS lu d liu gn nh mt c s d liu, bao gm nhiu dng, mi dng li c mt s nh danh duy nht: A record store database Data Record ID 1 Array of bytes 2 Array of bytes 3 Array of bytes Mt tp cc bn ghi (sau ny gi l RecordStore) l tp hp cc Record c sp xp c th t. Mi Record khng th ng c lp m n phi thuc vo mt RecordStore no , cc thao tc trn Record phi thng qua RecordStore cha n. Khi to ra mt Record trong RecordStore, Record c gn mt s nh danh kiu s nguyn gi l Record ID. Record u tin c to ra s c gn Record ID l 1 v s tng thm 1 cho cc Record tip theo. Cn ch rng Record ID khng phi l ch mc (index), cc thao tc xa Record trong RecordStore s khng gy nn vic tnh ton li cc Record ID ca cc Record hin c cng nh khng lm thay i Record ID ca cc Record c to mi, v d: khi ta xa record id 3 khi thm mt record mi s c id l 4. Data l mt dy cc byte i din cho d liu cn lu. Tn c dung phn bit cc RecordStore trong b cc MIDlet (MIDlet suite). Cn ch khi nim MIDlet suite l tp cc MIDlet c chung khng gian tn (name space), c th chia s cng ti nguyn (nh RecordStore), cc bin tnh (static variable) trong cc lp v cc MIDlet ny s c ng gi trong cng mt file .jar khi trin khai. Nu ng dng ca bn ch c mt MIDlet th cc RecordStore c s dng cng phn bit ln nhau bng cc tn. Tn ca RecordStore c th di n 32 k t Unicode v l duy nht trong mt MIDlet suite.

Trang: 62

Record Management System

ng lin th hin vic truy xut Record store do MIDlet to ra, ng nt t l Record store do MIDlet khc to ra. Trong MIDLET Suite One, MIDlet #1 v MIDlet #2 cng c th truy xut 4 Record store. MIDLET Suite One khng th truy xut Record store trong Suite Two. Trong MIDlet Suite One tn ca cc Record store l duy nhy, tuy nhin Record store trong cc MIDlet Suite khc nhau c th dng chung mt tn. Record Store cn c 2 thuc tnh l Version Number v Date/time Stamp, cc gi tr ny thay i khi thc hin thm, thay th hay xa mt record, ngoi ra cn c th dng c ch event handler (Listener) pht hin mi khi Record store b thay i. Version number l mt s integer, bit gi tr khi u bn cn gi hm getVersion() sau khi to mt Record store. Trang: 63

Record Management System Date/time Stamp l s long integer, l s miliseconds k t ngy 1 thng 1 nm 1970, bn c th bit c gi tr ny thng qua hm getLastModified(). 2. Cc vn lin quan n RMS a) Hn ch v kh nng lu tr ca thit b di ng Dung lng vng nh (non-volatile memory) dnh ring cho vic lu tr d liu trong RMS thay i ty theo thit b di ng. c t MIDP yu cu rng cc nh sn xut thit b di ng phi dnh ra vng nh c kch thc t nht 8K cho vic lu tr d liu trong RMS. c t khng nu gii hn trn cho mi Record. RMS cung cp cc API xc nh kch thc ca mi Record, tng dung lng ca RecordStore v kch thc cn li ca vng nh ny. Do trong qu trnh pht trin cc ng dng J2ME bn phi cn nhc trong vic s dng vng nh ny. b) Tc truy xut d liu Cc thao tc trn vng nh ny (non-volatile memory) tt nhin s chm hn nhiu khi bn truy xut d liu trn b nh RAM (volatile memory). N s ging nh tc c cng v tc c t RAM ca my tnh bn. V vy trong k thut lp trnh bn phi thng xuyn cache d liu v cc thao tc lin quan n RMS ch thc hin tp trung mt ln (lc khi ng hay ng ng dng). c) C ch lung an ton Nu RecordStore ca bn ch c s dng bi mt MIDlet, bn khng phi lo lng v vn ny v RMS s dnh ring mt Thread thc hin cc thao tc trn RecordStore. Tuy nhin nu c nhiu MIDlet v Thread cng chia s mt RecordStore th phi ch n k thut lp trnh Thread m bo khng c s xung t d liu. 3. Cc hm API trong RMS RecordStore khng c hm khi to. RecordStore Class: javax.microedition.rms.RecordStore Method Description static RecordStore M mt Recordstore, c tham s to openRecordStore(String Record store nu n cha tn ti. recordStoreName, boolean createIfNecessary) void closeRecordStore() ng RecordStore. static void deleteRecordStore(String Xa RecordStore. recordStoreName) static String[] listRecordStores() Danh sch cc RecordStore trong MIDlet suite. int addRecord(byte[] data, int offset, int Thm mt record vo RecordStore. numBytes) void setRecord(int recordId, byte[] t hoc thay th mt record trong newData, int offset, int numBytes) RecordStore. Trang: 64

Record Management System void deleteRecord(int recordId) byte[] getRecord(int recordId) int getRecord(int recordId, byte[] buffer, int offset) int getRecordSize(int recordId) int getNextRecordID() int getNumRecords() long getLastModified() int getVersion() String getName() int getSize() int getSizeAvailable() RecordEnumeration enumerateRecords( RecordFilter filter, RecordComparator comparator, boolean keepUpdated) void addRecordListener (RecordListener listener) void removeRecordListener (RecordListener listener) Xa mt record trong RecordStore. Ly dy byte cha record. Ly ni dung ca record vo dy byte. Kch thc record. Ly record id ca record mi . S lng cc record. Thi gian thay i gn nht. Version ca RecordStore. Tn ca RecordStore. Kch thc ca RecordStore. S byte trng cho RecordStore. Xy dng enumeration dng duyt recordstore Add a listener to detect record store Remove listener.

Chng ta hy cng xem qua 2 v d n gin ca vic c ghi record trong RecordStore. V d 1: c v ghi i tng string (ReadWrite.java)
/*-------------------------------------------------* ReadWrite.java * * Read and write to the record store. * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class ReadWrite extends MIDlet { private RecordStore rs = null; static final String REC_STORE = "db_1"; public ReadWrite() { openRecStore(); // Create the record store // Write a few records and read them back writeRecord("J2ME and MIDP"); writeRecord("Wireless Technology"); readRecords(); closeRecStore(); // Close record store deleteRecStore(); // Remove the record store

Trang: 65

Record Management System


} public void destroyApp( boolean unconditional ) { } public void startApp() { // There is no user interface, go ahead and shutdown destroyApp(false); notifyDestroyed(); } public void pauseApp() { } public void openRecStore() { try { // Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); } catch (Exception e) { db(e.toString()); } } public void closeRecStore() { try { rs.closeRecordStore(); } catch (Exception e) { db(e.toString()); } } public void deleteRecStore() { if (RecordStore.listRecordStores() != null) { try { RecordStore.deleteRecordStore(REC_STORE); } catch (Exception e) { db(e.toString()); } } } public void writeRecord(String str)

Trang: 66

Record Management System


{ byte[] rec = str.getBytes(); try { rs.addRecord(rec, 0, rec.length); } catch (Exception e) { db(e.toString()); } } public void readRecords() { try { byte[] recData = new byte[50]; int len; for (int i = 1; i <= rs.getNumRecords(); i++) { len = rs.getRecord( i, recData, 0 ); System.out.println("Record #" + i + ": " + new String(recData, 0, len)); System.out.println("------------------------------"); } } catch (Exception e) { db(e.toString()); } } /*-------------------------------------------------* Simple message to console for debug/errors * When used with Exceptions we should handle the * error in a more appropriate manner. *-------------------------------------------------*/ private void db(String str) { System.err.println("Msg: " + str); } }

Trang: 67

Record Management System y l output ca v d 1:

Hm m mt recordstore
public void openRecStore() { try { // Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); } catch (Exception e) { db(e.toString()); } }

Vi tham s true, hm s to mt RecordStore nu n cha tn ti. Trong hm WriteRecord, trc khi lu vo RecordStore, cn phi chuyn i kiu string thnh dy byte:
byte[] rec = str.getBytes(); ... rs.addRecord(rec, 0, rec.length);

Trong hm ReadRecord, chng ta cng cn c mt dy byte:


byte[] recData = new byte[50]; ... len = rs.getRecord( i, recData, 0 );

Cn lu l trong v d trn do bit trc kch thc ca string nn khai bo dy byte va , trong thc t ta nn kim tra kch thc ca record khai bo dy byte cn thit trnh pht sinh li, do hm ReadRecord c th sa li nh sau:

Trang: 68

Record Management System


for (int i = 1; i <= rs.getNumRecords(); i++) { if (rs.getRecordSize(i) > recData.length) recData = new byte[rs.getRecordSize(i)]; len = rs.getRecord(i, recData, 0); System.out.println("Record #" + i + ": " + new String(recData, 0, len)); System.out.println("------------------------------"); }

Nu ch cn c ghi nhng on text vo record, th v d trn l qu . Tuy nhin, thc t l ta cn lu nhng gi tr khc: String, int, boolean, v.v Trong v d 2 ny, chng trnh s s dng stream c v ghi record. Vic s dng stream gip chng ta linh ng v nng cao hiu qu ca vic c v ghi d liu vo RecordStore. V d 2: c v ghi s dng stream (ReadWriteStreams.java)
/*-------------------------------------------------* ReadWriteStreams.java * * Use streams to read and write Java data types * to the record store. * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class ReadWriteStreams extends MIDlet { private RecordStore rs = null; // Record store static final String REC_STORE = "db_1"; // Name of record store public ReadWriteStreams() { openRecStore(); // Create the record store writeTestData(); // Write a series of records readStream(); // Read back the records closeRecStore(); // Close record store deleteRecStore(); // Remove the record store } public void destroyApp( boolean unconditional ) { } public void startApp() { // There is no user interface, go ahead and shutdown destroyApp(false); notifyDestroyed(); } public void pauseApp() { }

Trang: 69

Record Management System


public void openRecStore() { try { // Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); } catch (Exception e) { db(e.toString()); } } public void closeRecStore() { try { rs.closeRecordStore(); } catch (Exception e) { db(e.toString()); } } public void deleteRecStore() { if (RecordStore.listRecordStores() != null) { try { RecordStore.deleteRecordStore(REC_STORE); } catch (Exception e) { db(e.toString()); } } } /*-------------------------------------------------* Create three arrays to write to record store *-------------------------------------------------*/ public void writeTestData() { String[] strings = {"Text 1", "Text 2"}; boolean[] booleans = {false, true}; int[] integers = {1 , 2}; writeStream(strings, booleans, integers); } /*-------------------------------------------------* Write to record store using streams. *-------------------------------------------------*/ public void writeStream(String[] sData, boolean[] bData,int[] iData)

Trang: 70

Record Management System


{ try { // Write data into an internal byte array ByteArrayOutputStream strmBytes = new ByteArrayOutputStream(); // Write Java data types into the above byte array DataOutputStream strmDataType = new DataOutputStream(strmBytes); byte[] record; for (int i = 0; i < sData.length; i++) { // Write Java data types strmDataType.writeUTF(sData[i]); strmDataType.writeBoolean(bData[i]); strmDataType.writeInt(iData[i]); // Clear any buffered data strmDataType.flush(); // Get stream data into byte array and write record record = strmBytes.toByteArray(); rs.addRecord(record, 0, record.length); // Toss any data in the internal array so writes // starts at beginning (of the internal array) strmBytes.reset(); } strmBytes.close(); strmDataType.close(); } catch (Exception e) { db(e.toString()); } } /*-------------------------------------------------* Read from the record store using streams *-------------------------------------------------*/ public void readStream() { try { // Careful: Make sure this is big enough! // Better yet, test and reallocate if necessary byte[] recData = new byte[50]; // Read from the specified byte array ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData); // Read Java data types from the above byte array DataInputStream strmDataType = new DataInputStream(strmBytes); for (int i = 1; i <= rs.getNumRecords(); i++) {

Trang: 71

Record Management System


// Get data into the byte array rs.getRecord(i, recData, 0); // Read back the data types System.out.println("Record #" + i); System.out.println("UTF: " + strmDataType.readUTF()); System.out.println("Boolean: " + strmDataType.readBoolean()); System.out.println("Int: " + strmDataType.readInt()); System.out.println("--------------------"); // Reset so read starts at beginning of array strmBytes.reset(); } strmBytes.close(); strmDataType.close(); } catch (Exception e) { db(e.toString()); } } /*-------------------------------------------------* Simple message to console for debug/errors * When used with Exceptions we should handle the * error in a more appropriate manner. *-------------------------------------------------*/ private void db(String str) { System.err.println("Msg: " + str); } }

Output ca v d 2:

Trang: 72

Record Management System

D liu ghi vo record trong v d 2 gm:


String[] strings = {"Text 1", "Text 2"}; boolean[] booleans = {false, true}; int[] integers = {1 , 2};

Hm WriteStream s ghi d liu vo RecordStore


// Write data into an internal byte array ByteArrayOutputStream strmBytes = new ByteArrayOutputStream(); // Write Java data types into the above byte array DataOutputStream strmDataType = new DataOutputStream(strmBytes); byte[] record; for (int i = 0; i < sData.length; i++) { // Write Java data types strmDataType.writeUTF(sData[i]); strmDataType.writeBoolean(bData[i]); strmDataType.writeInt(iData[i]); // Clear any buffered data strmDataType.flush(); // Get stream data into byte array and write record record = strmBytes.toByteArray(); rs.addRecord(record, 0, record.length); // Toss any data in the internal array so writes // starts at beginning (of the internal array) strmBytes.reset(); }

Hm s dng hai stream l strmBytes l mt mng byte s ghi vo RecordSotre v strmDataType cha d liu. Nh vy qu trnh ghi d liu vo RecordStore c thc hin thng qua cc bc: Cp pht stream. Ghi d liu vo stream. Flush stream. Chuyn i stream data thnh mng byte. Ghi mng byte vo RecordStore. ng stream. Vic c cc d liu t record n gin ch cn thay OutStream thnh InputStream:
byte[] recData = new byte[50]; // Read from the specified byte array ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData); // Read Java data types from the above byte array DataInputStream strmDataType = new DataInputStream(strmBytes); for (int i = 1; i <= rs.getNumRecords(); i++) { // Get data into the byte array rs.getRecord(i, recData, 0); // Read back the data types System.out.println("Record #" + i);

Trang: 73

Record Management System


System.out.println("UTF: " + strmDataType.readUTF()); System.out.println("Boolean: " + strmDataType.readBoolean()); System.out.println("Int: " + strmDataType.readInt()); System.out.println("--------------------"); // Reset so read starts at beginning of array strmBytes.reset(); }

y, chng ti khai bo mt mng byte recData (ging vi strmBytes), sau khi gi hm


rs.getRecord(i, recData, 0);

Chng ta c mng byte lc u chng trnh ghi vo record, sau dng InputStream strmDataType c ng kiu d liu:
System.out.println("UTF: " + strmDataType.readUTF()); System.out.println("Boolean: " + strmDataType.readBoolean()); System.out.println("Int: " + strmDataType.readInt());

Lu : khi s dng DataOutputStream v DataInputStream, cn phi c v ghi theo ng th t, nu khng s khng ra kt qu mong mun. 4. Duyt Record vi RecordEnumeration Trong cc v d trc duyt cc record ta s dng vng lp:
for (int i = 1; i <= rs.getNumRecords(); i++) { rs.getRecord(i, recData, 0); ... }

Ngoi ra cn mt cch khc duyt RecordStore l s dung RecordEnumeration. Lp ny cung cp cc phng thc duyt cc record trong RecordStore mt cch nhanh chng. Di y l on code duyt ton b RecordStore:
RecordEnumeration re = rs.enumerateRecords(null,null,false); while (re.hasNextElement()) { // Get the next record into a String String str = new String(re.nextRecord()); ... do something ... }

Trong on code trn s dng nextRecord() duyt n record sau , ngoi ra cn c previousRecord() gip duyt v record trc . Nu mun bt u ti v tr cui cng ca recordstore ta ch cn gi hm previousRecord() ngay khi m recordstore, n s tr v dng cui cng. RecordEnumeration c duy tr mt index ca cc record. Khi recordstore c s thay i th RecordEnumeration c th hot dng khng chnh xc, do chng ta cn phi gi hm reindex() mi khi recordstore c s thay i.

Trang: 74

Record Management System RecordEnumeration API RecordEnumeration Interface: javax.microedition.rms.RecordEnumeration Method Description int numRecords() S lng record trong enumeration byte[] nextRecord() Record tip theo int nextRecordId() Record ID ca record tip theo byte[] previousRecord() Record trc int previousRecordId() Record ID ca record trc boolean hasNextElement() Kim tra enumeration c record k tip Kim tra enumeration c record trc boolean hasPreviousElement() void keepUpdated(boolean t enumeration reindex sau khi co s keepUpdated) thay i Kim tra enumeration c t ng boolean isKeptUpdated() reindex() void rebuild() To li index void reset() a enumeration v record u tin void destroy() Gii phng ti nguyn c s dng bi enumeration 5. Sp xp cc record vi interface RecordComparator Interface ny gip ngi lp trnh so snh hai Record theo mt tiu ch no . Interface ny nh ngha phng thc compare vi tr u vo l hai mng cc byte th hin hai Record cn so snh. Phng thc ny tr v cc tr sau c nh ngha trong interface: EQUIVALENT: Nu hai Record bng nhau FOLLOWS: Nu Record th 1 ng sau Record th 2 PRECEDES: Nu Record th 1 ng trc Record th 2 Do RecrdComparator l mt interface nn khi s dng cn phi implements n:
public class Comparator implements RecordComparator { public int compare(byte[] rec1, byte[] rec2) { String str1 = new String(rec1), str2 = new String(rec2); int result = str1.compareTo(str2); if (result == 0) return RecordComparator.EQUIVALENT; else if (result < 0) return RecordComparator.PRECEDES; else return RecordComparator.FOLLOWS; } }

Sau ta s dng lp Comparator bng cch gn kt n vi RecordEnumeration:


// Create a new comparator for sorting Comparator comp = new Comparator(); // Reference the comparator when creating the result set

Trang: 75

Record Management System


RecordEnumeration re = rs.enumerateRecords(null,comp,false); // Iterate through the sorted results while (re.hasNextElement()) { String str = new String(re.nextRecord());

. Enumeration s s dng hm compare trong class Comparator sp xp cc record trong RecordStore. RecordComparator Interface: javax.microedition.rms.RecordComparator Method Description int compare(byte[] rec1, byte[] rec2) So snh quyt nh th t sp xp V d 3: chng trnh sp xp c bn
/*-------------------------------------------------* SimpleSort.java * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class SimpleSort extends MIDlet { private RecordStore rs = null; static final String REC_STORE = "db_1"; public SimpleSort() { openRecStore(); // Create the record store // Write a few records writeRecord("Sand Wedge"); writeRecord("One Wood"); writeRecord("Putter"); writeRecord("Five Iron"); // Read back with enumerator, sorting the results readRecords(); closeRecStore(); // Close record store deleteRecStore(); // Remove the record store } public void destroyApp( boolean unconditional ) { } public void startApp() { // There is no user interface, go ahead and shutdown destroyApp(false); notifyDestroyed(); } public void pauseApp()

Trang: 76

Record Management System


{ } public void openRecStore() { try { // Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); } catch (Exception e) { db(e.toString()); } } public void closeRecStore() { try { rs.closeRecordStore(); } catch (Exception e) { db(e.toString()); } } public void deleteRecStore() { if (RecordStore.listRecordStores() != null) { try { RecordStore.deleteRecordStore(REC_STORE); } catch (Exception e) { db(e.toString()); } } } public void writeRecord(String str) { byte[] rec = str.getBytes(); try { rs.addRecord(rec, 0, rec.length); } catch (Exception e) { db(e.toString()); } }

Trang: 77

Record Management System


public void readRecords() { try { if (rs.getNumRecords() > 0) { Comparator comp = new Comparator(); RecordEnumeration re = rs.enumerateRecords(null,comp, false); while (re.hasNextElement()) { String str = new String(re.nextRecord()); System.out.println(str); System.out.println("------------------------------"); } } } catch (Exception e) { db(e.toString()); } } /*-------------------------------------------------* Simple message to console for debug/errors * When used with Exceptions we should handle the * error in a more appropriate manner. *-------------------------------------------------*/ private void db(String str) { System.err.println("Msg: " + str); } } /*-------------------------------------------------| Comparator.java | | Compares two records to determine sort order *-------------------------------------------------*/ class Comparator implements RecordComparator { public int compare(byte[] rec1, byte[] rec2) { String str1 = new String(rec1), str2 = new String(rec2); int result = str1.compareTo(str2); if (result == 0) return RecordComparator.EQUIVALENT; else if (result < 0) return RecordComparator.PRECEDES; else return RecordComparator.FOLLOWS; } }

Trang: 78

Record Management System Trong on code trn trong hm readRecord(), khi to Enumeration ta tham chiu n i tng comp ca lp Comparator
Comparator comp = new Comparator(); RecordEnumeration re = rs.enumerateRecords(null, comp, false); while (re.hasNextElement()) { ... }

Khi enumerator to index cho RecordStore n s s dng hm compare() trn sp xp cc record. Output ca vi d 3:

V d trn ng trong trng hp d liu lu vo record l dng text, nu quay li v d 2 ta ghi nhiu kiu d liu vo trong mt record:
// Write Java data types to stream strmDataType.writeUTF("Text 1"); strmDataType.writeBoolean(true); strmDataType.writeInt(1);

Cc kiu d liu trn s c lu vo mt stream dng binary. Sau cc stream ny s c chuyn thnh mng v a vo recordstore:
// Get stream data into an array record = strmBytes.toByteArray(); // Write the array to a record rs.addRecord(record, 0, record.length);

on code trong v d 3 s chy sai khi p dng vi kiu d liu binary. gii quyt, ta cn phi vit li hm compare() th c hin chc nng chuyn i chui byte v sp xp ng kiu d liu.

Trang: 79

Record Management System Trong thc t, chng ta cn phi lu nhiu trng d liu trong mt record nh trong v d 2 (lu d liu kiu String, boolean, integer). Trong trng hp ny s c nhiu la chn sp xp cc record, v vic la chn ny ty thuc vo ng dng ca bn. Trong 2 v d sau y s thc thi interface RecordComparator sp xp record cha nhiu kiu d liu. Nhng v d ny s s dng cng d liu u vo, tuy nhin v d 4 s sp xp da vo kiu String, trong khi v d 5 s sp xp da vo kiu integer. y l d liu s lu vo recordstore:
String[] pets = {"duke", "tiger", "spike", "beauregard"}; boolean[] dog = {true, false, true, true}; int[] rank = {3, 0, 1, 2}; Khi lu vo recordstore s c dng nh sau: Record #1 "duke" true 3 Record #2 "tiger" false 0 Record #3 "spike" true 1 Record #4 "beauregard" true 2

y l l do v d 3 khng p ng c yu cu, do d liu lu vo khng cn l dng text, v hm String.CompareTo() trn ni dung ca record khng th sp xp d liu theo mong mun. Do , bn cn phi ly ra t mi record trng d liu m bn mun sp xp. Trong v d 4 s ly kiu String u mi record, v d 5 s ly kiu integer cui mi record. V d 4: StringSort.java
/*-------------------------------------------------* StringSort.java * * Sort records that contain multiple Java * data types. Sort using String type. * * Uses: Streams, Enumeration, RecordComparator * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class StringSort extends MIDlet { private RecordStore rs = null; // Record store static final String REC_STORE = "db_3"; // Name of record store public StringSort()

Trang: 80

Record Management System


{ openRecStore(); // Create the record store writeTestData(); // Write a series of records readStream(); // Read back the records closeRecStore(); // Close record store deleteRecStore(); // Remove the record store } public void destroyApp( boolean unconditional ) { } public void startApp() { // There is no user interface, go ahead and shutdown destroyApp(false); notifyDestroyed(); } public void pauseApp() { } public void openRecStore() { try { // Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); } catch (Exception e) { db(e.toString()); } } public void closeRecStore() { try { rs.closeRecordStore(); } catch (Exception e) { db(e.toString()); } } public void deleteRecStore() { if (RecordStore.listRecordStores() != null) { try { RecordStore.deleteRecordStore(REC_STORE); } catch (Exception e)

Trang: 81

Record Management System


{ db(e.toString()); } } } /*-------------------------------------------------* Create three arrays to write to record store *-------------------------------------------------*/ public void writeTestData() { String[] pets = {"duke", "tiger", "spike", "beauregard"}; boolean[] dog = {true, false, true, true}; int[] rank = {3, 0, 1, 2}; writeStream(pets, dog, rank); } /*-------------------------------------------------* Write to record store using streams. *-------------------------------------------------*/ public void writeStream(String[] sData, boolean[] bData,int[] iData) { try { // Write data into an internal byte array ByteArrayOutputStream strmBytes = new ByteArrayOutputStream(); // Write Java data types into the above byte array DataOutputStream strmDataType = new DataOutputStream(strmBytes); byte[] record; for (int i = 0; i < sData.length; i++) { // Write Java data types strmDataType.writeUTF(sData[i]); strmDataType.writeBoolean(bData[i]); strmDataType.writeInt(iData[i]); // Clear any buffered data strmDataType.flush(); // Get stream data into byte array and write record record = strmBytes.toByteArray(); rs.addRecord(record, 0, record.length); // Toss any data in the internal array so writes // starts at beginning (of the internal array) strmBytes.reset(); } strmBytes.close(); strmDataType.close(); } catch (Exception e) { db(e.toString()); }

Trang: 82

Record Management System


} /*-------------------------------------------------* Read from the record store using streams *-------------------------------------------------*/ public void readStream() { try { // Careful: Make sure this is big enough! // Better yet, test and reallocate if necessary byte[] recData = new byte[50]; // Read from the specified byte array ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData); // Read Java data types from the above byte array DataInputStream strmDataType = new DataInputStream(strmBytes); if (rs.getNumRecords() > 0) { ComparatorString comp = new ComparatorString(); int i = 1; RecordEnumeration re = rs.enumerateRecords(null, comp, false); while (re.hasNextElement()) { // Get data into the byte array rs.getRecord(re.nextRecordId(), recData, 0); // Read back the data types System.out.println("Record #" + i++); System.out.println("Name: " + strmDataType.readUTF()); System.out.println("Dog: " + strmDataType.readBoolean()); System.out.println("Rank: " + strmDataType.readInt()); System.out.println("--------------------"); // Reset so read starts at beginning of array strmBytes.reset(); } comp.compareStringClose(); // Free enumerator re.destroy(); } strmBytes.close(); strmDataType.close(); } catch (Exception e) { db(e.toString()); } } /*-------------------------------------------------* Simple message to console for debug/errors * When used with Exceptions we should handle the

Trang: 83

Record Management System


* error in a more appropriate manner. *-------------------------------------------------*/ private void db(String str) { System.err.println("Msg: " + str); } } /*-------------------------------------------------| Compares two strings to determine sort order | Each record passed in contains multiple Java data | types - use only the String data for sorting *-------------------------------------------------*/ class ComparatorString implements RecordComparator { private byte[] recData = new byte[10]; // Read from a specified byte array private ByteArrayInputStream strmBytes = null; // Read Java data types from the above byte array private DataInputStream strmDataType = null; public void compareStringClose() { try { if (strmBytes != null) strmBytes.close(); if (strmDataType != null) strmDataType.close(); } catch (Exception e) { } } public int compare(byte[] rec1, byte[] rec2) { String str1, str2; try { // If either record is larger than our buffer, reallocate int maxsize = Math.max(rec1.length, rec2.length); if (maxsize > recData.length) recData = new byte[maxsize]; // Read record #1 // Only need one read because the string to // sort on is the first "field" in the record strmBytes = new ByteArrayInputStream(rec1); strmDataType = new DataInputStream(strmBytes); str1 = strmDataType.readUTF(); // Read record #2 strmBytes = new ByteArrayInputStream(rec2); strmDataType = new DataInputStream(strmBytes); str2 = strmDataType.readUTF();

Trang: 84

Record Management System


// Compare record #1 and #2 int result = str1.compareTo(str2); if (result == 0) return RecordComparator.EQUIVALENT; else if (result < 0) return RecordComparator.PRECEDES; else return RecordComparator.FOLLOWS; } catch (Exception e) { return RecordComparator.EQUIVALENT; } } }

Trng d liu u tin trong cc record l kiu string, - dng lm tiu ch sp xp. Trc ht ta ly chui cn so snh trong dy byte bng hm readUTF() , ri dng compareTo() trong class String sp xp:
// Read record #1 // Only need one read because the string to // sort on is the first "field" in the record ... str1 = strmDataType.readUTF(); // Read record #2 ... str2 = strmDataType.readUTF(); // Compare record #1 and #2 int result = str1.compareTo(str2); ...

Output ca v d 4:

Trang: 85

Record Management System

V d 5: integer sort
/*-------------------------------------------------* IntSort.java * * Sort records that contain multiple Java * data types. Sort using integer type. * * Uses: Streams, Enumeration, RecordComparator * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class IntSort extends MIDlet { private RecordStore rs = null; // Record store static final String REC_STORE = "db_4"; // Name of record store public IntSort() { openRecStore(); // Create the record store writeTestData(); // Write a series of records readStream(); // Read back the records closeRecStore(); // Close record store deleteRecStore(); // Remove the record store } public void destroyApp( boolean unconditional ) { } public void startApp() { // There is no user interface, go ahead and shutdown destroyApp(false); notifyDestroyed(); } public void pauseApp() { } public void openRecStore() { try { // Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); } catch (Exception e) {

Trang: 86

Record Management System


db(e.toString()); } } public void closeRecStore() { try { rs.closeRecordStore(); } catch (Exception e) { db(e.toString()); } } public void deleteRecStore() { if (RecordStore.listRecordStores() != null) { try { RecordStore.deleteRecordStore(REC_STORE); } catch (Exception e) { db(e.toString()); } } } /*-------------------------------------------------* Create three arrays to write to record store *-------------------------------------------------*/ public void writeTestData() { String[] pets = {"duke", "tiger", "spike", "beauregard"}; boolean[] dog = {true, false, true, true}; int[] rank = {3, 0, 1, 2}; writeStream(pets, dog, rank); } /*-------------------------------------------------* Write to record store using streams. *-------------------------------------------------*/ public void writeStream(String[] sData, boolean[] bData,int[] iData) { try { // Write data into an internal byte array ByteArrayOutputStream strmBytes = new ByteArrayOutputStream(); // Write Java data types into the above byte array DataOutputStream strmDataType = new DataOutputStream(strmBytes);

Trang: 87

Record Management System


byte[] record; for (int i = 0; i < sData.length; i++) { // Write Java data types strmDataType.writeUTF(sData[i]); strmDataType.writeBoolean(bData[i]); strmDataType.writeInt(iData[i]); // Clear any buffered data strmDataType.flush(); // Get stream data into byte array and write record record = strmBytes.toByteArray(); rs.addRecord(record, 0, record.length); // Toss any data in the internal array so writes // starts at beginning (of the internal array) strmBytes.reset(); } strmBytes.close(); strmDataType.close(); } catch (Exception e) { db(e.toString()); } } /*-------------------------------------------------* Read from the record store using streams *-------------------------------------------------*/ public void readStream() { try { // Careful: Make sure this is big enough! // Better yet, test and reallocate if necessary byte[] recData = new byte[50]; // Read from the specified byte array ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData); // Read Java data types from the above byte array DataInputStream strmDataType = new DataInputStream(strmBytes); if (rs.getNumRecords() > 0) { ComparatorInt comp = new ComparatorInt(); int i = 1; RecordEnumeration re = rs.enumerateRecords(null,comp, false); while (re.hasNextElement()) { // Get data into the byte array rs.getRecord(re.nextRecordId(), recData, 0); // Read back the data types System.out.println("Record #" + i++);

Trang: 88

Record Management System


System.out.println("Name: " + strmDataType.readUTF()); System.out.println("Dog: " + strmDataType.readBoolean()); System.out.println("Rank: " + strmDataType.readInt()); System.out.println("--------------------"); // Reset so read starts at beginning of array strmBytes.reset(); } comp.compareIntClose(); // Free enumerator re.destroy(); } strmBytes.close(); strmDataType.close(); } catch (Exception e) { db(e.toString()); } } /*-------------------------------------------------* Simple message to console for debug/errors * When used with Exceptions we should handle the * error in a more appropriate manner. *-------------------------------------------------*/ private void db(String str) { System.err.println("Msg: " + str); } } /*-------------------------------------------------| Compares two integers to determine sort order | Each record passed in contains multiple Java data | types - use only the integer data for sorting *-------------------------------------------------*/ class ComparatorInt implements RecordComparator { private byte[] recData = new byte[10]; // Read from a specified byte array private ByteArrayInputStream strmBytes = null; // Read Java data types from the above byte array private DataInputStream strmDataType = null; public void compareIntClose() { try { if (strmBytes != null) strmBytes.close(); if (strmDataType != null) strmDataType.close(); } catch (Exception e)

Trang: 89

Record Management System


{ } } public int compare(byte[] rec1, byte[] rec2) { int x1, x2; try { // If either record is larger than our buffer, reallocate int maxsize = Math.max(rec1.length, rec2.length); if (maxsize > recData.length) recData = new byte[maxsize]; // Read record #1 // We want the integer from the record, which is // the last "field" thus we must read the String // and boolean to get to the integer strmBytes = new ByteArrayInputStream(rec1); strmDataType = new DataInputStream(strmBytes); strmDataType.readUTF(); strmDataType.readBoolean(); x1 = strmDataType.readInt(); // Here's our data // Read record #2 strmBytes = new ByteArrayInputStream(rec2); strmDataType = new DataInputStream(strmBytes); strmDataType.readUTF(); strmDataType.readBoolean(); x2 = strmDataType.readInt(); // Here's our data // Compare record #1 and #2 if (x1 == x2) return RecordComparator.EQUIVALENT; else if (x1 < x2) return RecordComparator.PRECEDES; else return RecordComparator.FOLLOWS; } catch (Exception e) { return RecordComparator.EQUIVALENT; } } }

Trong v d ny ta vn s dng d liu ca v d 4, tiu ch sp xp l theo kiu integer, do trc ht ta phi ly d liu trong dy byte. Tuy nhin,,c mt lu l do d liu ta cn ly nm cui cng trong dy byte do ra cn phi c theo th t, tc l phi c kiu String, boolean ri mi n integer:
// Read record #1 // We want the integer from the record, which is // the last "field" thus we must read the String // and boolean to get to the integer

Trang: 90

Record Management System


... strmDataType.readUTF(); strmDataType.readBoolean(); x1 = strmDataType.readInt(); // Here's our data // Read record #2 ... strmDataType.readUTF(); strmDataType.readBoolean(); x2 = strmDataType.readInt(); // Here's our data // Compare record #1 and #2 ...

Output ca v d 5:

6. Searching with RecordFilter Ngoi vic sp xp cc record (s dng RecordComparator), enumerator cn cung cp c ch lc (tm kim cc record tha mn mt iu kin no ). Khi s dng RecordComparator tt c cc record trong RecordStore u c lu trong mt result set. Nhng khi dng RecordFilter, ch c nhng tha mn iu kin mi c trong enumerator result set.
class SearchFilter implements RecordFilter { private String searchText = null; public SearchFilter(String searchText) { // This is the text to search for this.searchText = searchText.toLowerCase(); }

Trang: 91

Record Management System


public boolean matches(byte[] candidate) { String str = new String(candidate).toLowerCase(); // Look for a match if (searchText != null && str.indexOf(searchText) != -1) return true; else return false; } }

Trn y l mt class n gin thc thi interface RecordFilter. Class ny s c gn vi mt enumerator, v khi enumerator s dng hm matches() duyt ht recordstore ly ra nhng record cn tm:
// Create a new search filter SearchFilter search = new SearchFilter("search text"); // Reference the filter when creating the result set RecordEnumeration re = rs.enumerateRecords(search,null,false); // If there is at least one record in result set, a match was found if (re.numRecords() > 0) // Do something

RecordFilter Interface: javax.microedition.rms.RecordFilter Method Description boolean matches(byte[] candidate) Tm kim record tha mn mt iu kin no Sau y ta s xem qua chng trnh tm kim n gin s dng interface RecordFilter: V d 6:
/*-------------------------------------------------* SimpleSearch.java * * Display a Form and Textbox for searching records * Each record contains a String object. * * Uses: Enumeration, RecordFilter *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; import javax.microedition.lcdui.*; public class SimpleSearch extends MIDlet implements CommandListener { private Display display; // Reference to Display object private Form fmMain; // The main form private StringItem siMatch; // The matching text, if any private Command cmFind; // Command to search record store private Command cmExit; // Command to insert items private TextField tfFind; // Search text as requested by user

Trang: 92

Record Management System


private RecordStore rs = null; // Record store static final String REC_STORE = "db_6"; // Name of record store public SimpleSearch() { display = Display.getDisplay(this); // Define textfield, stringItem and commands tfFind = new TextField("Find", "", 10, TextField.ANY); siMatch = new StringItem(null, null); cmExit = new Command("Exit", Command.EXIT, 1); cmFind = new Command("Find", Command.SCREEN, 2); // Create the form, add commands fmMain = new Form("Record Search"); fmMain.addCommand(cmExit); fmMain.addCommand(cmFind); // Append textfield and stringItem fmMain.append(tfFind); fmMain.append(siMatch); // Capture events fmMain.setCommandListener(this); //-------------------------------// Open and write to record store //-------------------------------openRecStore(); // Create the record store writeTestData(); // Write a series of records } public void destroyApp( boolean unconditional ) { closeRecStore(); // Close record store deleteRecStore(); } public void startApp() { display.setCurrent(fmMain); } public void pauseApp() { } public void openRecStore() { try { // Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); } catch (Exception e) { db(e.toString()); } } public void closeRecStore()

Trang: 93

Record Management System


{ try { rs.closeRecordStore(); } catch (Exception e) { db(e.toString()); } } public void deleteRecStore() { if (RecordStore.listRecordStores() != null) { try { RecordStore.deleteRecordStore(REC_STORE); } catch (Exception e) { db(e.toString()); } } } /*-------------------------------------------------* Create array of data to write into record store *-------------------------------------------------*/ public void writeTestData() { String[] golfClubs = { "Wedge...good from the sand trap", "Truong dai hoc khoa hoc tu nhien", "Putter...only on the green", "Hoc mon LTUDM rat bo ich!"}; writeRecords(golfClubs); } /*-------------------------------------------------* Write to record store. *-------------------------------------------------*/ public void writeRecords(String[] sData) { byte[] record; try { // Only add the records once if (rs.getNumRecords() > 0) return; for (int i = 0; i < sData.length; i++) { record = sData[i].getBytes(); rs.addRecord(record, 0, record.length);

Trang: 94

Record Management System


} } catch (Exception e) { db(e.toString()); } } /*-------------------------------------------------* Search using enumerator and record filter *-------------------------------------------------*/ private void searchRecordStore() { try { // Record store is not empty if (rs.getNumRecords() > 0) { // Setup the search filter with the user requested text SearchFilter search = new SearchFilter(tfFind.getString()); RecordEnumeration re = rs.enumerateRecords(search, null, false); // A match was found using the filter if (re.numRecords() > 0) // Show match in the stringItem on the form siMatch.setText(new String(re.nextRecord())); re.destroy(); // Free enumerator } } catch (Exception e) { db(e.toString()); } } public void commandAction(Command c, Displayable s) { if (c == cmFind) { searchRecordStore(); } else if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } /*-------------------------------------------------* Simple message to console for debug/errors * When used with Exceptions we should handle the * error in a more appropriate manner. *-------------------------------------------------*/

Trang: 95

Record Management System


private void db(String str) { System.err.println("Msg: " + str); } } /*-------------------------------------------------* Search for text within a record * Each record passed in contains only text (String) *-------------------------------------------------*/ class SearchFilter implements RecordFilter { private String searchText = null; public SearchFilter(String searchText) { // This is the text to search for this.searchText = searchText.toLowerCase(); } public boolean matches(byte[] candidate) { String str = new String(candidate).toLowerCase(); // Look for a match if (searchText != null && str.indexOf(searchText) != -1) return true; else return false; } }

Sau khi vit class SearchFilter, ta to mt instance search, khi khai bo class RecordEnumeration s tham chiu n instance trn. Khi ch c nhng record tha mn iu kin (trong hm matches()) mi hin th trong result set: // Setup the search filter with the user requested text SearchFilter search = new SearchFilter(tfFind.getString()); RecordEnumeration re =rs.enumerateRecords(search,null,false); // A match was found using the filter if (re.numRecords() > 0) siMatch.setText(new String(re.nextRecord()));

Trang: 96

Record Management System Output:

Lu v d trn khng phn bit ch hoa thng. Tip theo y chng ta li xt thm mt v d v tm kim record. V d 7:
/*-------------------------------------------------* SearchStreams.java * * Display a Form and Textbox for searching records * Each record contains multiple Java data types * (String, boolean and integer). Use the String * data for searching * * Uses: Enumeration, RecordFilter *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; import javax.microedition.lcdui.*; public class SearchStreams extends MIDlet implements CommandListener { private Display display; // Reference to Display object private Form fmMain; // The main form private StringItem siMatch; // The matching text, if any private Command cmFind; // Command to search record store private Command cmExit; // Command to insert items private TextField tfFind; // Search text private RecordStore rs = null; // Record store static final String REC_STORE = "db_7"; // Name of record store

Trang: 97

Record Management System


public SearchStreams() { display = Display.getDisplay(this); // Define textfield, stringItem and commands tfFind = new TextField("Find", "", 10, TextField.ANY); siMatch = new StringItem(null, null); cmExit = new Command("Exit", Command.EXIT, 1); cmFind = new Command("Find", Command.SCREEN, 2); // Create the form, add commands fmMain = new Form("Record Search"); fmMain.addCommand(cmExit); fmMain.addCommand(cmFind); // Append textfield and stringItem fmMain.append(tfFind); fmMain.append(siMatch); // Capture events fmMain.setCommandListener(this); //-------------------------------// Open and write to record store //-------------------------------openRecStore(); // Create the record store writeTestData(); // Write a series of records } public void destroyApp( boolean unconditional ) { closeRecStore(); // Close record store deleteRecStore(); } public void startApp() { display.setCurrent(fmMain); } public void pauseApp() { } public void openRecStore() { try { // Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); } catch (Exception e) { db(e.toString()); } } public void closeRecStore() { try {

Trang: 98

Record Management System


rs.closeRecordStore(); } catch (Exception e) { db(e.toString()); } } public void deleteRecStore() { if (RecordStore.listRecordStores() != null) { try { RecordStore.deleteRecordStore(REC_STORE); } catch (Exception e) { db(e.toString()); } } } /*-------------------------------------------------* Create three arrays to write into record store *-------------------------------------------------*/ public void writeTestData() { String[] pets = {"duke - big, goofy golden retriever", "tiger - we found in a field", "spike - loves chasing car tires", "beauregard - barks at everything"}; boolean[] dog = {true, false, true, true}; int[] rank = {3, 0, 1, 2}; writeStream(pets, dog, rank); } /*-------------------------------------------------* Write to record store using streams. *-------------------------------------------------*/ public void writeStream(String[] sData, boolean[] bData,int[] iData) { try { // Only add the records once if (rs.getNumRecords() > 0) return; // Write data into an internal byte array ByteArrayOutputStream strmBytes = new ByteArrayOutputStream(); // Write Java data types into the above byte array DataOutputStream strmDataType = new DataOutputStream(strmBytes); byte[] record;

Trang: 99

Record Management System


for (int i = 0; i < sData.length; i++) { // Write Java data types strmDataType.writeUTF(sData[i]); strmDataType.writeBoolean(bData[i]); strmDataType.writeInt(iData[i]); // Clear any buffered data strmDataType.flush(); // Get stream data into byte array and write record record = strmBytes.toByteArray(); rs.addRecord(record, 0, record.length); // Toss any data in the internal array so writes // starts at beginning (of the internal array) strmBytes.reset(); } strmBytes.close(); strmDataType.close(); } catch (Exception e) { db(e.toString()); } } /*-------------------------------------------------* Search using enumerator and record filter *-------------------------------------------------*/ private void searchRecordStore() { try { // Record store is not empty if (rs.getNumRecords() > 0) { // Setup the search filter with the user requested text SearchFilter search = new SearchFilter(tfFind.getString()); RecordEnumeration re = rs.enumerateRecords(search, null, false); // A match was found using the filter if (re.numRecords() > 0) { // Read from the specified byte array ByteArrayInputStream strmBytes = new ByteArrayInputStream(re.nextRecord()); // Read Java data types from the above byte array DataInputStream strmDataType = new DataInputStream(strmBytes); // Show matching result in stringItem component on form siMatch.setText(strmDataType.readUTF()); search.searchFilterClose(); // Close record filter strmBytes.close(); // Close stream

Trang: 100

Record Management System


strmDataType.close(); // Close stream re.destroy(); // Free enumerator } } } catch (Exception e) { db(e.toString()); } } public void commandAction(Command c, Displayable s) { if (c == cmFind) { searchRecordStore(); } else if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } /*-------------------------------------------------* Simple message to console for debug/errors * When used with Exceptions we should handle the * error in a more appropriate manner. *-------------------------------------------------*/ private void db(String str) { System.err.println("Msg: " + str); } } /*-------------------------------------------------* Search for text within a record * Each record passed in contains multiple Java data * types (String, boolean and integer) *-------------------------------------------------*/ class SearchFilter implements RecordFilter { private String searchText = null; // Read from a specified byte array private ByteArrayInputStream strmBytes = null; // Read Java data types from the above byte array private DataInputStream strmDataType = null; public SearchFilter(String searchText) { // This is the text to search for this.searchText = searchText.toLowerCase(); } // Cleanup public void searchFilterClose()

Trang: 101

Record Management System


{ try { if (strmBytes != null) strmBytes.close(); if (strmDataType != null) strmDataType.close(); } catch (Exception e) { } } public boolean matches(byte[] candidate) { String str = null; try { strmBytes = new ByteArrayInputStream(candidate); strmDataType = new DataInputStream(strmBytes); // Although 3 pieces of data were written to // the record (String, boolean and integer) // we only need one read because the string to // search is the first "field" in the record str = strmDataType.readUTF().toLowerCase(); } catch (Exception e) { return false; } // Look for a match if (str != null && str.indexOf(searchText) != -1) return true; else return false; } }

Cng c chc nng tm kim nhng v d 7 khc v d 6 ch d liu lu vo record. v d ny d liu lu vo record di dng dy byte, v trong dy byte ny ta li lu nhiu trng d liu:
strmDataType.writeUTF(sData[i]); // Write Strings strmDataType.writeBoolean(bData[i]); // Write booleans strmDataType.writeInt(iData[i]); // Write integers

Trong hm searchRecordStore() ta to mt b tm kim v enumerator. Phng thc matches() (ca class SearchFilter) s c gi bi enumerator v c p dng cho mi record trong RecordStore. c c ng d liu cn dng ta cn dng hai stream mt dng c dy byte trong record v mt dng c ng kiu d liu trong dy byte .
strmBytes = new ByteArrayInputStream(candidate); strmDataType = new DataInputStream(strmBytes); str = strmDataType.readUTF().toLowerCase();

Trang: 102

Record Management System


Sau chui ny s c so snh vi searchText: if (str != null && str.indexOf(searchText) != -1) return true; else return false;

Output:

7. Notification of Changes with RecordListener pht hin cc thay i cng nh thm vo cc Record trong RecordStore, RMS cung cp giao din RecordListener. Giao din ny nh ngha 3 phng thc, cc phng thc c 2 tr vo l mt i tng kiu RecordStore v mt s int cha recordID. Cc phng thc l: RecordListener Interface: javax.microedition.rms.RecordListener Method Description void recordAdded(RecordStore c gi khi thm 1 record recordStore, int recordId) void recordChanged(RecordStore recordStore, int recordId) void recordDeleted(RecordStore recordStore, int recordId) V d 8: s dng RecordListener Trang: 103 c gi khi record bi thay i c gi khi record b xa

Record Management System

/*-------------------------------------------------* RmsListener.java * * Test the RMS listener methods * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class RmsListener extends MIDlet { private RecordStore rs = null; static final String REC_STORE = "db_8"; public RmsListener() { // Open record store and add listener openRecStore(); rs.addRecordListener(new TestRecordListener()); // Initiate actions that will wake up the listener writeRecord("J2ME and MIDP"); updateRecord("MIDP and J2ME"); deleteRecord(); closeRecStore(); // Close record store deleteRecStore(); // Remove the record store } public void destroyApp( boolean unconditional ) { } public void startApp() { // There is no user interface, go ahead and shutdown destroyApp(false); notifyDestroyed(); } public void pauseApp() { } public void openRecStore() { try { // Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); } catch (Exception e) { db(e.toString()); } }

Trang: 104

Record Management System


public void closeRecStore() { try { rs.closeRecordStore(); } catch (Exception e) { db(e.toString()); } } public void deleteRecStore() { if (RecordStore.listRecordStores() != null) { try { RecordStore.deleteRecordStore(REC_STORE); } catch (Exception e) { db(e.toString()); } } } public void writeRecord(String str) { byte[] rec = str.getBytes(); try { rs.addRecord(rec, 0, rec.length); } catch (Exception e) { db(e.toString()); } } public void updateRecord(String str) { try { rs.setRecord(1, str.getBytes(), 0, str.length()); } catch (Exception e) { db(e.toString()); } } public void deleteRecord() { try

Trang: 105

Record Management System


{ rs.deleteRecord(1); } catch (Exception e) { db(e.toString()); } } /*-------------------------------------------------* Simple message to console for debug/errors * When used with Exceptions we should handle the * error in a more appropriate manner. *-------------------------------------------------*/ public void db(String str) { System.err.println("Msg: " + str); } } /*-------------------------------------------------* Listen for updates to the record store *-------------------------------------------------*/ class TestRecordListener implements RecordListener { public void recordAdded(RecordStore recordStore, int recordId) { try { System.out.println("Record with ID#: " + recordId + "added to RecordStore: " + recordStore.getName()); } catch (Exception e) { System.err.println(e); } } public void recordDeleted(RecordStore recordStore, int recordId) { try { System.out.println("Record with ID#: " + recordId + "deleted from RecordStore: " + recordStore.getName()); } catch (Exception e) { System.err.println(e); } } public void recordChanged(RecordStore recordStore, int recordId) {

Trang: 106

Record Management System


try { System.out.println("Record with ID#: " + recordId + "changed in RecordStore: " + recordStore.getName()); } catch (Exception e) { System.err.println(e); } } }

Output:

8. Exception Handling Cc phng thc trong API ca RMS ngoi vic pht sinh cc ngoi l thng thng n mi trng chy (runtime enviroment). RMS cn nh ngha thm cc ngoi l trong gi javax.microedition.rms nh sau: InvalidRecordIDException: Ngoi l ny pht sinh ra khi khng th thao tc trn Record v RecordID khng thch hp. RecordStoreFullException: Ngoi l ny pht sinh ra khi khng cn vng nh. RecordStoreNotFoundException: Ngoi l ny pht sinh ra khi m mt RecordStore khng tn ti. RecordStoreNotOpenException: Ngoi l ny pht sinh ra khi thao tc trn mt RecordStore b ng. RecordStoreException: y l lp cha ca 4 lp trn, ngoi l ny m t li chung nht trong qu trnh thao tc vi RMS.

Trang: 107

The Generic Connection Framework

VI.

The Generic Connection Framework

Vi kch thc hn 200 kb v hn 100 class v interfaces trong gi java.io, java.net ca J2SE s chim hu ht b nh vn d nh b ca nhng thit b i ng. Do Sun khng th k tha nhng gi ny vo trong J2ME, m h xy dng mt chun l Generic Connection Framework (GCF). GCF s gip cho cc thit b di ng c th truy xut c cc ti nguyn mng, cng nh cc ti nguyn khc m a ch ca chng c xc nh bng URL. Generic Connection Framework bao gm mt tp hp cc interfaces c khai bo trong package javax.microedition.io. Hnh v sau th hin mi quan h gia cc interfaces:

C mt class chnh l Connector v 7 interfaces c nh ngha trong GCF. T hnh v ta d dng nhn thy GCF h tr kt ni dng datagram(packet) v stream. Class Connector c dng m kt ni n mt ti nguyn no thng qua phng thc open c khai bo nh sau:
Connector.Open("protocol:address;parameters");

1. Nhng protocol c h tr trong GCF GCF h tr nhiu loi protocol khc nhau. Khi c yu cu to mt kt ni, class Connector s s dng phng thc Class.forName() tm kim mt class ph hp vi protocol . Nu tm thy mt i tng s c tr v v thc thi interface Connection (hnh v). Di y l cch m cc kt ni khc nhau: Connector.Open("socket://www.corej2me.com.com:55"); Connector.Open("http://www.corej2me.com"); Connector.Open("datagram://www.corej2me.com:1000"); Connector.Open("file://makefile.txt"); M mt kt ni to kt ni, GCF cung cp cho ta n 7 phng thc:
Connector (public class Connector) public static Connection open(String name)

Trang: 108

The Generic Connection Framework


public static Connection open(String name) public static Connection open(String name, int mode, boolean timeouts) public static DataInputStream openDataInputStream(String name) public static DataOutputStream openDataOutputStream(String name) public static InputStream openInputStream(String name) public static OutputStream openOutputStream(String name)

Di y l on code m kt ni thng qua stream


// Create a ContentConnection String url = "http://www.corej2me.com" ContentConnection connection = (ContentConnection) Connector.open(url); // With the connection, open a stream InputStream iStrm = connection.openInputStream(); // ContentConnection includes a length method int length = (int) connection.getLength(); if (length != -1) { byte imageData[] = new byte[length]; // Read the data into an array iStrm.read(imageData); }

Tuy nhin, ngoi class ContentConnection, ta cng c th m mt kt ni trc tip bng InputStream. Sau y l on code cho php ti v mt bc nh v sau to li bc nh :
InputStream iStrm = (InputStream) Connector.openInputStream(url); Image img = null; try { ByteArrayOutputStream bStrm = new ByteArrayOutputStream(); int ch; while ((ch = iStrm.read()) != -1) bStrm.write(ch); // Place into image array byte imageData[] = bStrm.toByteArray(); // Create the image from the byte array img = Image.createImage(imageData, 0, imageData.length); } finally { // Clean up if (iStrm != null) iStrm.close(); }

Trang: 109

The Generic Connection Framework Lu , trong on code trn do khng s dng class ContentConnection, nn ta s khng bit c kch thc ca d liu s ti v. khc phc vn ny, ngi ta s dng ByteArrayOutputStream lu d liu ti v. Di y l v d n gin, u tin MIDlet s download v hin th hnh nh ti v. MIDlet s d dng ByteArrayOutputStream cha d liu ti v:
/*-------------------------------------------------* DownloadImage.java * * Download and view a png file *-------------------------------------------------*/ import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; import java.io.*; public class DownloadImage extends MIDlet implements CommandListener { private Display display; private TextBox tbMain; private Form fmViewPng; private Command cmExit; private Command cmView; private Command cmBack; public DownloadImage() { display = Display.getDisplay(this); // Create the textbox, allow maximum of 50 characters tbMain = new TextBox("Enter url", "http://localhost/intel.png", 55, 0); // Create commands and add to textbox cmExit = new Command("Exit", Command.EXIT, 1); cmView = new Command("View", Command.SCREEN, 2); tbMain.addCommand(cmExit); tbMain.addCommand(cmView ); // Set up a listener for textbox tbMain.setCommandListener(this); // Create the form that will hold the image fmViewPng = new Form(""); // Create commands and add to form cmBack = new Command("Back", Command.BACK, 1); fmViewPng.addCommand(cmBack); // Set up a listener for form fmViewPng.setCommandListener(this); }

Trang: 110

The Generic Connection Framework

public void startApp() { display.setCurrent(tbMain); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} /*-------------------------------------------------* Process events *-------------------------------------------------*/ public void commandAction(Command c, Displayable s) { // If the Command button pressed was "Exit" if (c == cmExit) { destroyApp(false); notifyDestroyed(); } else if (c == cmView) { // Download image and place on the form try { Image im; if ((im = getImage(tbMain.getString())) != null) { ImageItem ii = new ImageItem(null, im, ImageItem.LAYOUT_DEFAULT, null); // If there is already an image, set (replace) it if (fmViewPng.size() != 0) fmViewPng.set(0, ii); else // Append the image to the empty form fmViewPng.append(ii); } else fmViewPng.append("Unsuccessful download."); // Display the form with image display.setCurrent(fmViewPng); } catch (Exception e) { System.err.println("Msg: " + e.toString()); } } else if (c == cmBack) {

Trang: 111

The Generic Connection Framework


display.setCurrent(tbMain); } } /*-------------------------------------------------* Open connection and download png into a byte array. *-------------------------------------------------*/ private Image getImage(String url) throws IOException { InputStream iStrm = (InputStream) Connector.openInputStream(url); Image im = null; try { ByteArrayOutputStream bStrm = new ByteArrayOutputStream(); int ch; while ((ch = iStrm.read()) != -1) bStrm.write(ch); // Place into image array byte imageData[] = bStrm.toByteArray(); // Create the image from the byte array im = Image.createImage(imageData, 0, imageData.length); } finally { // Clean up if (iStrm != null) iStrm.close(); } return (im == null ? null : im); } }

Trang: 112

The Generic Connection Framework Mt textbox s cho php nhp a ch URL

Sau khi ti v, hnh nh s c hin th

2. H tr giao thc HTTP trong MIDP n y th bn d bit c rng GCF h tr nhiu kiu kt ni v pht trin ng dng MIDlet ti v v hin th hnh nh. Trong phn ny, s bn su hn v s h tr HTTP

Trang: 113

The Generic Connection Framework ca GCF. u tin, hy cp nht li s quan h gia cc interfaces trong GCF thy c v tr ca http:

c t ca phin bn MIDP 1.0 ch h tr HTTP, trong khi phin bn hin ti MIDP 2.0 h tr HTTP v HTTPS, cung cp kh nng bo mt tt hn. Cc hm API c khai bo trong HttpConnection (cho HTTP) v trong HttpConnections (cho HTTP v HTTPS).

a) Request and response protocols


C HTTP v HTTPS u gi request v response. My client gi request, cn server s tr v response. Client request bao gm 3 phn sau: Request method Header Body Request method nh ngha cch m d liu s c gi n server. C 3 phng thc c cung cp sn l GET, POST, HEADER. Khi s dng Get, d liu cn request s nm trong URL. Vi Post d liu gi t client s c phn thnh cc stream ring bit. Trong khi , Header s khng gi d liu yu cu ln server, thay vo header ch request nhng meta information v server. GET v POST l hai phng thc request kh ging nhau, tuy nhin do GET gi d liu thng qua URL nn s b gii hn, cn POST s dng nhng stream ring bit nn s khc phc c hn ch ny. V d v vic m HTTP Connection thng qua GET
String url = "http://www.corej2me.com?size=large"; HttpConnection http = null; http = (HttpConnection) Connector.open(url); http.setRequestMethod(HttpConnection.GET);

Nhng Header field s cho php ta truyn cc tham s t client n server. Cc header field thng dng l If-Modified-Since, Accept, and User Agent. Bn c th t cc

Trang: 114

The Generic Connection Framework field ny thng qua phng thc setRequestProperty(). Di y l v d dng setRequestProperty(), ch c nhng d liu thay i sau ngy 1 thng 1 nm 2005 mi c gi v t server:
String url = "http://www.corej2me.com\somefile.txt"; HttpConnection http = null; http = (HttpConnection) Connector.open(url); http.setRequestMethod(HttpConnection.GET); // Set header field as key-value pair http.setRequestProperty("If-Modified-Since", "Sat, 1 Jan 2005 12:00:00 GMT"); Body cha ni dung m bn mun gi ln server. V d v s dng POST v gi d liu t client thng qua stream: String url = "http://www.corej2me.com", tmp = "test data here"; OutputStream ostrm = null; HttpConnection http = null; http = (HttpConnection) Connector.open(url); http.setRequestMethod(HttpConnection.POST); // Send client body ostrm = http.openOutputStream(); byte bytes[] = tmp.getBytes(); for(int i = 0; i < bytes.length; i++) { os.write(bytes[i]); } os.flush();

Sau khi nhn c v s l yu cu t pha client, server s ng gi v gi v pha client. Cng nh client request, server cng gm 3 phn sau: Status line Header Body Status line s thng bo cho client kt qu ca request m client gi cho server. HTTP phn loi status line thnh cc nhm sau y: 1xx is informational 2xx is success 3xx is redirection 4xx is client error 5xx is server error Status line bao gm version ca HTTP trn server, status code, v on text i din cho status code. V d:
"HTTP/1.1 200 OK" "HTTP/1.1 400 Bad Request" "HTTP/1.1 500 Internal Server Error"

Header. Khng ging nh header ca client, server c th gi data thng qua header. Sau y l nhng phng thc dng ly thng tin Header m server gi v:
String getHeaderField(int n) Get header field value looking up by index String getHeaderField(String name) Get header field value looking up by name String getHeaderFieldKey(int n) Get header field key using index

Trang: 115

The Generic Connection Framework Server c th tr v nhiu Header field. Trong trng hp ny, phng thc u tin s cho ly header field thng qua index ca n. Cn phng thc th hai ly ni dung header field da vo tn ca header field. Cn nu mun bit tn (key) ca header field, c th dng phng thc th 3 trn. Sau y l v d v 3 phng thc trn, trong trng hp server gi v chui "content-type=text/plain". Method Return value http.getHeaderField(0) "text-plain" http.getHeaderField("content"text-plain" type") http.getHeaderFieldKey(0) "content-type" Body: Cng ging nh client, server gi hu ht nhng thng tin trong phn body cho client. Client dng input stream c kt qu tr v t server. b) The HttpConnection API Nh cp trn, ta s s dng HttpConnection API thit lp kt ni trong MIDP. Di y l nhng API trong HttpConnection: Method long getDate() long getExpiration() String getFile() int getHeaderField(int n) String getHeaderField(String name) long getHeaderFieldDate(String name, long def) int getHeaderFieldInt(String name, int def) String getHeaderFieldKey(int n) String getHost() long getLastModified() String getPort() String getProtocol() String getQuery() String getRef() String getRequestMethod() String getRequestProperty(String key) int getResponseCode() Description Get header field date Gets header field expiration Gets filename from the URL Gets header field value looking up by index Gets header field value looking up by name Gets named field as a long (representing the date) Gets named field as an integer Gets header field key using index Gets host from the URL Gets last-modified field value Gets port from the URL Gets protocol from the URL Gets the query string (only valid with GET request) Gets the reference portion of URL Gets the current setting of the request method (GET, POST or HEAD) Gets the current setting of a request property Gets the response code (numeric value) Trang: 116

The Generic Connection Framework String getResponseMessage() String getURL() void setRequestMethod(String method) void setRequestProperty(String key, String value) Gets the response message (text value) Gets the entire URL Sets the request method (GET, POST or HEAD) Sets a request property (header information)

V d: Chng ta s to mt MIDlet s dng HttpConnection ti v v hin th ni dung ca file text. Qua v d bn s hiu cch client gi request v ly response ca server. MIDlet cng s dng mt s phng thc trong HttpConnection thu thp thng tin v server: port, content type .. .
/*-------------------------------------------------* FileViewer.java *-------------------------------------------------*/ import javax.microedition.midlet.*; import javax.microedition.io.*; import javax.microedition.lcdui.*; import java.io.*; public class FileViewer extends MIDlet implements CommandListener { private Display display; private Form fmMain; private Command cmExit; private Command cmView; private String url = "http://localhost/text.txt"; public FileViewer() { display = Display.getDisplay(this); // Create exitcommand cmExit = new Command("Exit", Command.EXIT, 1); cmView = new Command("View", Command.SCREEN, 2); // Create the form and add commands fmMain = new Form("File Viewer"); fmMain.addCommand(cmExit); fmMain.addCommand(cmView); fmMain.setCommandListener(this); } public void startApp() { display.setCurrent(fmMain); }

Trang: 117

The Generic Connection Framework

/*-------------------------------------------------* Process events *-------------------------------------------------*/ public void commandAction(Command c, Displayable s) { // If the Command button pressed was "Exit" if (c == cmExit) { destroyApp(false); notifyDestroyed(); } else if (c == cmView) { // Download image and place on the form try { String str; if ((str = readFile()) != null) { // Delete form contents for (int i = fmMain.size(); i > 0; i--) fmMain.delete(0); // Append downloaded string fmMain.append("" + str); } } catch (Exception e) { System.err.println("Msg: " + e.toString()); } } } /*-------------------------------------------------* Read file *-------------------------------------------------*/ private String readFile() throws IOException { HttpConnection http = null; InputStream iStrm = null; String str = null; try { // Create the connection http = (HttpConnection) Connector.open(url); //---------------// Client Request

Trang: 118

The Generic Connection Framework


//---------------// 1) Send request method http.setRequestMethod(HttpConnection.GET); // 2) Send header information (this header is optional) http.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0"); // 3) Send body/data - No data for this request //---------------// Server Response //---------------System.out.println("url: " + url); System.out.println("-------------------------"); // 1) Get status Line System.out.println("Msg: " + http.getResponseMessage()); System.out.println("Code: " + http.getResponseCode()); System.out.println("-------------------------"); // 2) Get header information if (http.getResponseCode() == HttpConnection.HTTP_OK) { System.out.println("key 0: " + http.getHeaderFieldKey(0)); System.out.println("key 1 : " + http.getHeaderFieldKey(1)); System.out.println("key 2: " + http.getHeaderFieldKey(2)); System.out.println("-------------------------"); System.out.println("value (field) 0: " + http.getHeaderField(0)); System.out.println("value (field) 1: " + http.getHeaderField(1)); System.out.println("value (field) 2: " + http.getHeaderField(2)); System.out.println("-------------------------"); // 3) Get data (show the file contents) iStrm = http.openInputStream(); int length = (int) http.getLength(); if (length != -1) { // Read data in one chunk byte serverData[] = new byte[length]; iStrm.read(serverData); str = new String(serverData); } else // Length not available... { ByteArrayOutputStream bStrm = new ByteArrayOutputStream(); // Read data one character at a time int ch; while ((ch = iStrm.read()) != -1)

Trang: 119

The Generic Connection Framework


bStrm.write(ch); str = new String(bStrm.toByteArray()); bStrm.close(); } //----------------------------// Show connection information //----------------------------System.out.println("Host: " + http.getHost()); System.out.println("Port: " + http.getPort()); System.out.println("Type: " + http.getType()); } } finally { // Clean up if (iStrm != null) iStrm.close(); if (http != null) http.close(); } return str; } public void pauseApp() {} public void destroyApp(boolean unconditional) { } }

Trang: 120

The Generic Connection Framework Output

Console output

Trang: 121

The Generic Connection Framework 3. Accessing a Java servlet V d di y s ch cho bn tng bc cch truy truy xut java servlet. Bc u, client s truyn tham s cho servlet yu cu tr v ngy thng theo nh dng. Servlet s tr v kt qu, v s hin ln mn hnh. y l kt qu cho chui: yyyy.MM.dd+'at'+hh:mm:ss+zzz"

Trong hnh trn, ta thy phn kt qu c time zones l ICT, do ta truyn tham s zzz, nu chuyn thnh zzzz ly full text ca time zones th kt qu s thay i nh sau:

Trang: 122

The Generic Connection Framework Calling Servlet Yu cu gi servlet s uc khai bo bn trong commandAction(), v s c thc hin khi button cmRqst c kch hot:
/*-------------------------------------------------* Call the servlet *-------------------------------------------------*/ public void commandAction(Command c, Displayable s) { if (c == cmRqst) { try { serverMsg = null; callServlet(); if (serverMsg != null) fmMain.append(serverMsg); } catch (Exception e) { System.err.println("Msg: " + e.toString()); } } else if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } Di y l on code cho phng thc callServlet(), ch rng request ca client s dng request method l GET,: /*-------------------------------------------------* Call the servlet *-------------------------------------------------*/ private void callServlet() throws IOException { HttpConnection http = null; InputStream iStrm = null; boolean ret = false; // Examples - Data is passed at the end of url for GET String url = "http://localhost:8080/j2me/dateformatservlet?format=MMMM.dd.yyyy+''+hh:mm+aa"; // String url = "http://localhost:8080/j2me/dateformatservlet?format=yyyy.MM.dd+'at'+hh:mm:ss+zzz"; try { http = (HttpConnection) Connector.open(url); //----------------

Trang: 123

The Generic Connection Framework


// Client Request //---------------// 1) Send request method http.setRequestMethod(HttpConnection.GET); // 2) Send header information - none // 3) Send body/data - data is at the end of URL //---------------// Server Response //---------------iStrm = http.openInputStream(); // Three steps are processed in this method call ret = processServerResponse(http, iStrm); } finally { // Clean up if (iStrm != null) iStrm.close(); if (http != null) http.close(); } // Process request failed, show alert if (ret == false) showAlert(errorMsg); }

Code cho servlet, hu ht cc phng thc u c bit trong doPost(), bin format dng lu request t client, sau servlet s gi SimpleDateFormat to ra kt qu ph hp vi request:
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.Date; import java.text.SimpleDateFormat; import java.util.TimeZone; import java.util.Locale; public class DateFormatServlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

Trang: 124

The Generic Connection Framework


{ doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String format = request.getParameter("format"); SimpleDateFormat simpleDate = new SimpleDateFormat(format); Date dt = new Date(); PrintWriter out = response.getWriter(); response.setContentType("text/html"); out.println(simpleDate.format(dt)); out.close(); } public String getServletInfo() { return "DateFormatServlet"; } }

MIDlet nhn kt qu tr v t servlet, trc ht phi kim tra status line vi server v c kt tr v kt qu hay khng (HTTP_OK). Do khng c thng tin header nn s tin hnh ly kt qu t input stream:
/*-------------------------------------------------* Process a response from a server *-------------------------------------------------*/ private boolean processServerResponse(HttpConnection http, InputStream iStrm) throws IOException { //Reset error message errorMsg = null; // 1) Get status Line if (http.getResponseCode() == HttpConnection.HTTP_OK) { // 2) Get header information - none // 3) Get body (data) int length = (int) http.getLength(); String str; if (length != -1) { byte servletData[] = new byte[length]; iStrm.read(servletData); str = new String(servletData); }

Trang: 125

The Generic Connection Framework


else // Length not available... { ByteArrayOutputStream bStrm = new ByteArrayOutputStream(); int ch; while ((ch = iStrm.read()) != -1) bStrm.write(ch); str = new String(bStrm.toByteArray()); bStrm.close(); } // Save the server message serverMsg = str; return true; } else // Use message from the servlet errorMsg = new String( http.getResponseMessage()); return false; }

Trang: 126

Ph lc

Ph lc
Bng 1: Tng s class v interface trong CLDC Tn gi Miu t java.io Qun l vic xut nhp ca h thng java.lang Cc lp Java c bn java.util Cc lp h tr vic tnh thi gian, qun l tp hp v.v javax.microedition Qun l kt ni Bng 2: Cc lp b sung trong MIDP 1.0 Tn gi Miu t javax.microedition.rms Qun l vic lu tr d liu javax.microedition.midlet Giao din trung gian gia Midlet v mi trng Midlet ang chy javax.microedition.io H tr HTTP javax.microedition.lcdui H tr giao din ngi dng Bng 3: Tng s class v interface trong CDC Tn gi Miu t java.io Qun l vic xut nhp ca h thng java.lang Cc lp Java c bn java.lang.ref Cc lp h tr b thu gom rc ca JVM java.lang.reflect H tr tnh nng reflection trong Java java.math H tr cc php tnh trong ton hc java.net H tr mng java.security Cung cp cc tnh nng bo mt java.security.cert H tr cc chng thc trong bo mt java.text Cung cp cc lp h tr thao tc trn text java.util Cc lp h tr vic tnh thi gian, qun l tp hp v.v java.util.jar H tr thao tc trn file Jar java.util.zip H tr thao tc trn file Zip javax.microedition Qun l kt ni S lng class v interface 18 38 10 10 S lng class v interface 10 2 1 24 S lng class v interface 62 77 5 12 1 23 36 4 13 47 7 9 10

Trang: 127

Ph lc

Tham kho: http://java.sun.com/j2me/ http://www.cs.armstrong.edu/burge/pdf/huc/01_J2ME_Overview.pdf http://www.onjava.com/pub/a/onjava/2001/03/08/J2ME.html http://developers.sun.com/techtopics/mobility/midp/articles/wtoolkit/ CLDC Specification (JSR-30) http://www.jcp.org/jsr/detail/30.jsp CLDC Next Generation (JSR-139) http://www.jcp.org/jsr/detail/139.jsp MIDP Specification (JSR-37) http://www.jcp.org/jsr/detail/37.jsp Mobile Information Device Next Generation (JSR-118) http://www.jcp.org/jsr/detail/132.jsp PDA Profile Specification (JSR-75) http://www.jcp.org/jsr/detail/75.jsp CDC Specification (JSR-36) http://www.jcp.org/jsr/detail/36.jsp Foundation Profile Specification (JSR-46) http://www.jcp.org/jsr/detail/46.jsp Personal Profile Specification (JSR-62) http://www.jcp.org/jsr/detail/62.jsp RMI Profile Specification (JSR-66) http://www.jcp.org/jsr/detail/66.jsp Java Game Profile (JSR-134) http://www.jcp.org/jsr/detail/134.jsp J2ME Multimedia API Specification (JSR-135) http://www.jcp.org/jsr/detail/135.jsp J2ME White Papers KVM http://java.sun.com/products/cldc/wp Applications for Mobile Devices http://java.sun.com/j2me/docs/pdf/midpwp.pdf J2ME Technologies J2ME http://java.sun.com/j2me CLDC and KVM http://java.sun.com/products/cldc MIDP http://java.sun.com/products/midp MIDP for Palm OS http://java.sun.com/ CDC and CVM http://java.sun.com/products/cdc

Trang: 128

Ph lc J2ME Development Kits J2ME Wireless Toolkit http://java.sun.com/products/j2mewtoolkit Metrowerks CodeWarrior for J2ME http://www.metrowerks.com/desktop/java Zucotto WHITEboard SDK http://www.zucotto.com/whiteboard/index.html RIM BlackBerry Java IDE http://developers.rim.net/tools/jde/index.shtml J2ME Developer Resources Java Developer Connection http://developer.java.sun.com/developer Java Wireless Developer Initiative http://java.sun.com/wireless Wireless Developer Network http://www.wirelessdevnet.com Micro Java Network http://www.microjava.com Java Mobile Community http://www.javamobile.org Java Enabled Phones and PDAs http://www.javamobiles.com KVM World http://www.kvmworld.com KVM-Interest Mailing List Archive http://archives.java.sun.com/kvm-interest.html XML Parsers for J2ME TinyXML Parser http://gibaradunn.srac.org/tiny NanoXML Parser http://nanoxml.sourceforge.net

Trang: 129

You might also like