+ All Categories

J2me

Date post: 15-Nov-2014
Category:
Upload: saptarshi9433
View: 11 times
Download: 0 times
Share this document with a friend
Popular Tags:
27
Saptarshi Chatterjee, email:[email protected], Ph 9433884727 Page 1 J2ME Java Platform, Micro Edition, or Java ME, is a Java platform designed for mobile devices and embedded systems. Target devices range from industrial controls to mobile phones and set-top boxes. Java ME was formerly known as Java 2 Platform, Micro Edition (J2ME). Java ME was designed by Sun Microsystems and is a replacement for a similar technology, Personal Java. Due to the limited size of mobile devices {pagers, mobile phones, and personal digital assistants (PDAs) set-top boxes} in regards to memory and resource availability, J2ME defines a limited version of the JVM. As a developer, you only need to develop applications targeting these devices and install them. Device manufacturers install and prepackage their devices with this JVM (not the traditional JVM, but the cut-down version and associated APIs). J2ME is divided into 3 parts: configurations, profiles, and optional APIs onfiguration is designed for a specific kind of device based on memory constraints and processor power. A configuration contains the JVM (not the traditional JVM, but the cut-down version) and some class libraries that can be easily ported to devices supporting the configuration. It also specifies a strict subset of the Java 2 Platform, Standard Edition (J2SE) APIs that will be used on the platform, as well as additional APIs that may be necessary. Device manufacturers are responsible for porting a specific configuration to their devices. C
Transcript
Page 1: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 1

J2ME

Java Platform, Micro Edition, or Java ME, is a Java platform designed for mobile devices and embedded systems.

Target devices range from industrial controls to mobile phones and set-top boxes. Java ME was formerly known

as Java 2 Platform, Micro Edition (J2ME).

Java ME was designed by Sun Microsystems and is a replacement for a similar technology, Personal Java.

Due to the limited size of mobile devices {pagers, mobile phones, and personal digital assistants (PDAs)

set-top boxes} in regards to memory and resource availability, J2ME defines a limited version of the JVM.

As a developer, you only need to develop applications targeting these devices and install them. Device

manufacturers install and prepackage their devices with this JVM (not the traditional JVM, but the cut-down

version and associated APIs).

J2ME is divided into 3 parts: configurations, profiles, and optional APIs

onfiguration is designed for a specific kind of device based on memory constraints and processor power. A

configuration contains the JVM (not the traditional JVM, but the cut-down version) and some class libraries

that can be easily ported to devices supporting the configuration. It also specifies a strict subset of the Java

2 Platform, Standard Edition (J2SE) APIs that will be used on the platform, as well as additional APIs that

may be necessary. Device manufacturers are responsible for porting a specific configuration to their devices.

C

Page 2: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 2

rofiles are more specific than configurations. A profile is based on a configuration and

Provides additional APIs, such as user interface, persistent storage, and whatever else is necessary to

develop running applications for the device. The configuration and profile are supplied by the device

manufacturers and they embedded them in the devices.

ptional APIs (for example File Connection Optional Package : javax.microedition.io.file , PIM Optional

Package : javax.microedition.pim.* ) define specific additional functionality. Optional packages are

traditionally not packaged by the device manufacturers, and you have to package and distribute them

with your application.

The most widely used profile and configuration that Sun provides are

Profile

Mobile Information Device Profile (MIDP)

Configuration

Connected Limited Device Configuration (CLDC) : CLDC is for devices with limited configurations.

I.e. devices that have only 128 to 512KB of memory available for Java applications. The JVM that it

provides is very limited and supports only a small number of traditional Java classes. (This limited JVM is

actually called the KVM.)

The latest versions of MIDP and CLDC are 2.1 and 1.1( As of 5th

May ,2009 ) , respectively. Not many

devices currently support these versions

Other Profiles and Configurations that sun provides are - Connected Device Configuration (CDC) .CDC is for devices

with at least 2MB of memory available and supports a more feature-rich JVM (but still not a standard JVM). MIDP

cannot be used with CDC devices. CDC devices get their own set of profiles, like the Foundation and Personal

profiles.

P O

Page 3: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 3

MIDlet MIDP applications are called MIDlets, a continuation of the naming theme begun by applets and servlets.

MIDlet Lifecycle

Mobile devices interact with a MIDlet using their own software called AMS (Application Management Software).

AMS is responsible for initializing, starting, pausing, resuming, and destroying a MIDlet. AMS may be responsible

for installing and removing a MIDlet, as well.

A MIDlet lifecycle have following steps...

1. startApp()

2. pauseApp()

3. destroyApp( boolean unconditional)

By default MIDlet is in the paused states. A MIDlet goes through the following states:

1. When the MIDlet is about to be run, an instance is created. The MIDlet’s constructor is

run, and the MIDlet is in the Paused state.

2. Next, the MIDlet enters the Active state after the application manager calls startApp().

3. While the MIDlet is Active, the application manager can suspend its execution by calling

pauseApp(). This puts the MIDlet back in the Paused state.

Page 4: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 4

4. While the MIDlet is in the Paused state, the application manager can call startApp() to

put it back into the Active state.

5. The application manager can terminate the execution of the MIDlet by calling destroyApp(), at which point the

MIDlet is destroyed and patiently awaits garbagecollection. A MIDlet can destroy itself by calling notifyDestroyed().

User Interface Architecture

MIDP 2.0 provides UI classes in two packages

1. javax.microedition.lcdui

2. javax.microedition.lcdui.game

1. javax.microedition.lcdui (Liquid Crystal Display User Interface) - This package can be divided

into two logical groups

i. High-level groups : The classes of the high-level group are perfect for development of

MIDlets that target the maximum number of devices, because these classes do not provide

exact control over their display.

ii. Low-level group: The classes of the low-level group are perfect for MIDlets where precise

control over the location and display of the UI elements is required. If your MIDlet is

developed using these classes, it may not be deployable on certain devices, because they

Page 5: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 5

require precise control over the way they look and feel. There are only two classes in this

group.

javax.microedition.lcdui contains following classes -

1. Alert – Best used in informational or error messages that stay on the screen for a short period of time

and then disappear

public Alert(String title, String alertText, Image alertImage, AlertType alertType)

Any or all of the parameters in the second constructor may be null

2. AlertType – There are 5 alert types i.e. ALARM, CONFIRMATION, ERROR, INFO, and WARNING. These

have different looks and feels.

3. Canvas

4. ChoiceGroup

public ChoiceGroup(String label, int choiceType)

public ChoiceGroup(String label, int choiceType, String[ ] stringElements, Image[ ] imageElements) Choice Types can be either EXCLUSIVE or MULTIPLE

5. Command

Command(String lebel, Command Type, Priority); In the SunJ2ME Wireless Toolkit emulator, commands are assigned to the two soft buttons. A soft button is a button on the device keypad with no predefined function. A soft button can serve a different purpose at

Page 6: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 6

different times. If there are more commands than there are soft buttons, the commands that don’t fit will be grouped into a menu that is assigned to one of the soft buttons. A simple priority scheme determines who wins when there are more commands than available screen space. Lower numbers indicate a higher priority.

The priority number facilitates the mapping of command to the corresponding button.

Command Types

6. DateField – Allows user to choose Date/Time from a calendar like format

public DateField(String label, int mode)

public DateField(String label, int mode, TimeZone timeZone)

Three types of modes

• DATE displays an editable date.

• TIME displays an editable time.

• DATE_TIME displays both a date and a time.

7. Display

The device’s display, as seen by the MIDlet, is represented by an instance of the Display class, accessed

from a factory method, getDisplay().Display’s main purpose is to keep track of what is currently shown,

which is an instance.

The Display can have only one Displayable element at one time, which becomes the current element on

display. The current element that is being displayed can be accessed using the method getCurrent(), which

returns an instance of a Displayable element. The static method getDisplay(MIDlet midlet) returns the

current display instance associated with your MIDlet method.

Page 7: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 7

8. Displayable

To show a UI element on a device screen, whether high- or low-level, it must implement the Displayable interface

.

both the Screen and Canvas classes and their subclasses implement this interface, as can be seen in Figure 3. The Graphics class does not implement this interface, because it deals with low-level 2D graphics that directly manipulate the device's screen

A Displayable class is a UI element that can be shown on the device's screen .It abstracts the display functions of an actual device's screen and makes them available to you. It provides methods to gain information about the screen and to show or change the current UI element that you want displayed. A MIDlet shows a Displayable UI element using the setCurrent(Displayable element) method of the Display class.

Illustration

Displayable d = new TextBox("TextBox", "Commander", 20, TextField.ANY);

Display.getDisplay(this) .setCurrent( d );

Displayable can hold instances of any of these 4 types (Alert, List, Form, and Textbox) of classes.

9. Font

10. Form A form is a collections of instances of the Item interface. There are eight Item types that can be added to a form.

StringItem, DateField, TextField, ChoiceGroup, Spacer, Gauge, ImageItem, CustomItem.

Page 8: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 8

public Form(String title)

Form Title are displayed at the top of the devices screen. Some of the widely used methods of the Form class are

public int append(Item item) , public void set(int index, Item item), public void insert(int index, Item item), public void

delete(int index).

When a form Item is deleted , the items below the deleted items automatically comes up anf fill that deleted index

space.

11. Gauge

public Gauge(String label, boolean interactive,int maxValue, int initialValue)

The gauge value itself can be set to one of the following: a. INCREMENTAL_UPDATING indicates that you have just accomplished something and the

gauge should be updated to reflect it.

b. INCREMENTAL_IDLE means that you want the gauge to be incremental but nothing is currently happening.

c. CONTINUOUS_RUNNING indicates a continuous gauge in its running mode.

d. CONTINUOUS_IDLE is used for a continuous gauge, indicating that no progress is currently being made.

12. Graphics

13. Image

14. ImageItem

Save the .PNG image in

C:\Documents and Settings\User\My Documents\NetBeansProjects\ [Your Project Name] \src

15. Item

16. List

Page 9: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 9

public List(String title, int type) public List(String title, int type,String[ ] stringElements, Image[] imageElements)

17. Screen

18. StringItem

19. TextBox

public TextBox(String title, String text, int maxSize, int constraints)

There are six constraint settings for restricting content: ANY, EMAILADDR, NUMERIC, PHONENUMBER, URL, and

DECIMAL.

Similarly, there are six constraint settings that affect the display. These are: PASSWORD, UNEDITABLE, SENSITIVE,

NON_PREDICTIVE, INITIAL_CAPS_WORD, and INITIAL_CAPS_SENTENCE. Not all of these settings may be functional

in all devices.

Can’t be appended in a form . Only way to be displayed is display.setCurrent(txtBox);

20. TextField

public TextField(String label, String text, int maxSize, int constraints)

Constraints are same as text box.

21. Ticker

A ticker is simply a bit of text that scrolls across the top of a Displayable; it is named after old fashioned stock tickers.All Displayables have a title and an optional ticker.

See http://wiki.netbeans.org/VisualMobileDesignerPalatteReference

and http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/package-summary.html for Details

Page 10: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 10

2. javax.microedition.lcdui.game – It only Contains the GameCanvas class . As the name

suggests GameCanvas is mainly used to develop java games for specific device.

Basic Programs

1) Alert

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hello; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.util.Date; /** * @author User */ public class alert extends MIDlet { public void startApp() { Alert timeAlert; timeAlert = new Alert("Alert!","Displayed Alert Message ", null,AlertType.INFO); timeAlert.setTimeout(500); //timeAlert.setTimeout(Alert.FOREVER); // timeAlert.setString(new Date().toString()); Display.getDisplay(this).setCurrent(timeAlert); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } }

Page 11: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 11

2) Text Box

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hello; import javax.microedition.lcdui.*; import javax.microedition.midlet.*; /** * @author User */ public class TextBox1 extends MIDlet { private TextBox txtBox1; private TextBox txtBox2; public void startApp() { txtBox1 = new TextBox("Username", "", 50, TextField.ANY); txtBox2 = new TextBox("Password","",5,TextField.NUMERIC | TextField.PASSWORD); Display display = Display.getDisplay(this); display.setCurrent(txtBox1); try{ Thread.sleep(500); } catch(Exception e) {} txtBox1.setString("Mr. Saptarhi "); try{ Thread.sleep(3000); } catch(Exception e) {} txtBox1.insert("Chatterjee", 20); try{ Thread.sleep(3000); } catch(Exception e) {} display.setCurrent(txtBox2); } public void pauseApp() { } public void destroyApp(boolean unconditional) {

Page 12: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 12

} }

3) Hello World

import javax.microedition.lcdui.*; import javax.microedition.midlet.*; public class HelloWorld extends MIDlet{ private Form form; private Display display; public void startApp(){ form = new Form("Hello World"); String msg = "Hello World!!!!!!!"; form.append(msg); display = Display.getDisplay(this); display.setCurrent(form); } public void pauseApp(){} public void destroyApp(boolean unconditional){ notifyDestroyed(); } }

4) Date Field

package hello; import javax.microedition.lcdui.*; import javax.microedition.midlet.MIDlet;

Page 13: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 13

import java.util.Date; import java.util.TimeZone; public class dateField extends MIDlet{ private Form form; private Display display; private DateField datein, dateout; private static final int DATE = 0; public dateField(){ datein = new DateField("Date In:", DateField.DATE, TimeZone.getTimeZone("GMT")); dateout = new DateField("Date Out:", DateField. DATE_TIME, TimeZone.getTimeZone("GMT")); } public void startApp(){ display = Display.getDisplay(this); Form form = new Form("Date Field"); form.append(datein); form.append(dateout); display.setCurrent(form); } public void pauseApp(){ } public void destroyApp(boolean destroy){ notifyDestroyed(); } }

5) Ticker /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hello; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; /** * @author User */ public class ticker extends MIDlet { Ticker t; Displayable d; public void startApp() {

Page 14: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 14

d = new TextBox("Username", "Saptarshi", 50, TextField.ANY); t= new Ticker("Saptarshi Chatterjee and Associates"); d.setTicker(t); Display.getDisplay(this).setCurrent(d); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } }

6) Form_TxtFld_chcGrp_dtFld_Gaug_Spcr_strItm_ImgItm

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hello; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; /** * @author User */ public class TxtFld_chcGrp_dtFld_Gaug_Spcr_strItm_ImgItm extends MIDlet { private Form form; private Gauge gauge; private Spacer spacer; private ImageItem imageItem; private TextField txtField; private DateField dateField; private StringItem stringItem; private ChoiceGroup choiceGroup; public TxtFld_chcGrp_dtFld_Gaug_Spcr_strItm_ImgItm() { form = new Form("Your Details"); // a StringItem is not editable stringItem = new StringItem("Your Id: ", "WXP-890"); form.append(stringItem);

Page 15: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 15

// you can accept Date, Time or DateTime formats dateField = new DateField("Your DOB: ", DateField.DATE); form.append(dateField); // similar to using a TextBox txtField = new TextField( "Your Name: ", "", 50, TextField.ANY); form.append(txtField); // similar to using a List choiceGroup = new ChoiceGroup( "Your meals: ", Choice.EXCLUSIVE, new String[] {"Veg", "Non-Veg"}, null); form.append(choiceGroup); // put some space between the items to segregate spacer = new Spacer(20, 20); form.append(spacer); // a gauge is used to show progress gauge = new Gauge("Step 1 of 3", false, 3, 1); form.append(gauge); // an image may not be found, // therefore the Exception must be handled // or ignored try { imageItem = new ImageItem( "Developed By: ", Image.createImage("/duke.gif"), ImageItem.LAYOUT_DEFAULT, "DuKe"); form.append(imageItem); } catch(Exception e) {} } public void startApp() { Display display = Display.getDisplay(this); display.setCurrent(form); } public void pauseApp() { } public void destroyApp(boolean unconditional) { }

Page 16: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 16

}

7) User Command

import javax.microedition.lcdui.*;

import javax.microedition.midlet.*;

public class CommandExample extends MIDlet implements CommandListener{

private Form form;

private Display display;

private Command ok, back, cancel, exit, help, item, screen, stop;

public CommandExample(){

form = new Form("Command Form");

screen = new Command("SCREEN", Command.SCREEN, 1);

back = new Command("BACK", Command.BACK, 2);

cancel = new Command("CANCEL", Command.CANCEL, 3);

ok = new Command("OK", Command.OK, 4);

help = new Command("HELP", Command.HELP, 5);

stop = new Command("STOP", Command.STOP, 6);

exit = new Command("EXIT", Command.EXIT, 7);

item = new Command("ITEM", Command.ITEM, 8);

}

public void startApp(){

display = Display.getDisplay(this);

form.addCommand(screen);

form.addCommand(back);

form.addCommand(cancel);

form.addCommand(ok);

form.addCommand(help);

form.addCommand(stop);

form.addCommand(exit);

form.addCommand(item);

form.setCommandListener(this); display.setCurrent(form);

}

public void pauseApp(){}

public void destroyApp(boolean destroy){

notifyDestroyed();

}

public void backCom(){

Alert back = new Alert("BACK Command",

Page 17: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 17

"Back Command Executed!", null, AlertType.INFO);

back.setTimeout(5000);

display.setCurrent(back, form);

}

public void okCom(){

Alert ok = new Alert("OK Command",

"OK Command Executed!", null, AlertType.INFO);

ok.setTimeout(5000);

display.setCurrent(ok, form);

}

public void cancelCom(){

Alert cancel = new Alert("CANCEL Command",

"Cancel Command Executed!", null, AlertType.INFO);

cancel.setTimeout(5000);

display.setCurrent(cancel, form);

}

public void exitCom(){

Alert exit = new Alert("EXIT Command",

"Exit Command Executed!", null, AlertType.INFO);

exit.setTimeout(5000);

display.setCurrent(exit, form);

}

public void commandAction(Command c, Displayable d) {

String label = c.getLabel();

if(label.equals("BACK")){

backCom();

} else if(label.equals("OK")){

okCom();

} else if(label.equals("CANCEL")){

cancelCom();

} else if(label.equals("EXIT")){

exitCom();

}

}

}

8) EMI calculator

Page 18: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 18

package hello; import javax.microedition.lcdui.*; import javax.microedition.midlet.MIDlet; public class interestRate extends MIDlet implements CommandListener { private float princ,yrs,intr,math; private int term; private Form form; private StringItem s1,s2,s3; private TextField t1,t2,t3; private String fi,ti,emi; private Alert a; public interestRate() { math=1; form = new Form("Your Details"); t1 = new TextField("loan : ", "", 15, TextField.DECIMAL); t2 = new TextField("month: ", "", 15, TextField.NUMERIC); t3 = new TextField("Intrst:", "", 15, TextField.DECIMAL); form.append(t1); form.append(t2); form.append(t3); // create some commands and add them // to this form form.addCommand( new Command("exit", Command.EXIT, 3)); form.addCommand( new Command("calc", Command.OK, 2)); form.setCommandListener(this); } // handle commands public void commandAction(Command com, Displayable dis) { String label = com.getLabel(); if("exit".equals(label)) notifyDestroyed(); else if("calc".equals(label)) calc();

Page 19: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 19

} public void calc() { try{ princ = Float.parseFloat(t1.getString()); term = Integer.parseInt(t2.getString()); intr = Float.parseFloat(t3.getString())/ 1200; yrs = term / 12; } catch(Exception e){math=0;} if(math==0) { a = new Alert("Enter values in Loan, Month & Interest"); Display.getDisplay(this).setCurrent(a); } else{ math=1; for(int i=0;i<term;i++) { math=math*(1/(1 + intr)); } math=princ * intr / (1 - math); emi=(math+""); math=(math*term)-princ; ti=(math+""); math=math/ yrs/ princ * 100; fi=(math+""); s1 = new StringItem("E.M.I. :", emi); s2 = new StringItem("Annula_flat_Intrst :", fi); s3 = new StringItem("Tot_Intrst_Amt :", ti); try{form.delete(3);form.delete(3);form.delete(3);}catch(Exception e){} form.append(s1); form.append(s2); form.append(s3); } } public void startApp() { Display display = Display.getDisplay(this); display.setCurrent(form); } public void pauseApp() { }

Page 20: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 20

public void destroyApp(boolean unconditional) { } }

Page 21: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 21

Low-Level API (Canvas & Graphics Classes)

The low-level API for MIDlets is composed of the Canvas and Graphics classes. The Canvas class is abstract; you

must create your own canvases to write/draw on by extending this class

Drawing Basics

Canvas (Display Area ,i.e. your LCD screen) You can find out the size of the Canvas by calling getWidth() and getHeight().The MIDP implementation calls a

Canvas’s paint() method when the contents of the Canvas need to be shown.

public void paint(Graphics g)

if you want to tell the Canvas to draw itself You can’t call paint() directly, because you don’t have a suitable

Graphics to pass to paint(). Instead, you need to call repaint(). The

public void repaint()

public void repaint(int x, int y, int width, int height)

first version of this method simply tells Canvas to paint everything.The second version is a way of only painting a

rectangular portion of the screen. This is useful when the image content is heavy .

Key Events Canvas includes a set of methods that handle interaction with the individual keys of a device. The following methods are automatically called whenever the user presses and releases a key.

protected void keyPressed(int keyCode)

protected void keyReleased(int keyCode)

Page 22: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 22

The key code that is passed to these methods will most likely be one of the constants defined in Graphics, from KEY_NUM0 through KEY_NUM9 and including KEY_STAR and KEY_POUND. Devices may have more keys than this, which will be returned as device-specific key codes.

Game Actions

MIDP offers a simple abstraction called a game action that makes it easier to map user key events to events that will be useful for games and other applications with specialized user interfaces. To find the game action for a key code, pass the key code to

public int getGameAction(int keyCode)

MIDP defines the following game actions:. UP, DOWN, LEFT, RIGHT, FIRE, GAME_A, GAME_B, GAME_C, or GAME_D on some devices the game actions UP, DOWN, LEFT and RIGHT may be mapped to 4-way navigation arrow keys. In this case, getKeyCode(UP) would return a device-dependent code for the up-arrow key. On other devices, a possible

mapping would be on the number keys 2, 4, 6 and 8. In this case, getKeyCode(UP) would return KEY_NUM2.

In both cases, the getGameAction() method would return the LEFT game action when the user presses the key that is a "natural left" on her device. Using game actions saves you from having to make these decisions yourself. Please Visit http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Canvas.htm for more details

9) Game Canvas

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hello; import javax.microedition.lcdui.Canvas; import javax.microedition.midlet.MIDlet; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Graphics; public class CanvasExample extends MIDlet { Canvas myCanvas; public CanvasExample() {

Page 23: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 23

myCanvas = new MyCanvas(); } public void startApp() { Display display = Display.getDisplay(this); // remember, Canvas is a Displayable so it can // be set on the display like Screen elements display.setCurrent(myCanvas); // force repaint of the canvas myCanvas.repaint(); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } } class MyCanvas extends Canvas { public void paint(Graphics g) { // create a 20x20 black square in the center // clear the screen first g.setColor(0xffffff); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(0x000000); // make sure it is black // draw the square, changed to rely on instance variables g.fillRect(x, y, 20, 20); } public void keyPressed(int keyCode) { // what game action does this key map to? int gameAction = getGameAction(keyCode); if(gameAction == RIGHT) { x += dx; } else if(gameAction == LEFT) { x -= dx;

Page 24: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 24

} else if(gameAction == UP) { y -= dy; } else if(gameAction == DOWN) { y += dy; } // make sure to repaint repaint(); } // starting coordinates private int x = getWidth()/2 - 10; private int y = getHeight()/2 - 10; // distance to move private int dx = 2; private int dy = 2; }

Page 25: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 25

Storing Records in Persistent Storage

In MIDP, persistent storage is centered around record stores. A record store is a small database

that contains pieces of data called records. The scope of a record store can either be limited to a single MIDlet suite

or be shared between MIDlet suites.

How a RecordStore Looks like

Opening, Closing, Removing and sharing Record Stores To open a record store

public static RecordStore openRecordStore(String recordStoreName, boolean createIfNecessary) throws RecordStoreException, RecordStoreFullException, RecordStoreNotFoundException To Close a RecordStore

Call closeRecordStore() method with corresponding record store object.

To delete a RecordStore

Call static method deleteRecordStore(String RecordStore name) To find out all the record stores available to a particular MIDlet suite,

call public static String[ ] listRecordStores()

Record stores also have an authorization mode. The default authorization mode is

AUTHMODE_PRIVATE, which means that a record store is only accessible from MIDlets in the

MIDlet suite that created the record store. Record stores can be shared by changing their authorization mode to

AUTHMODE_ANYYou can create a shared record store using an alternate openRecordStore() method in the

RecordStore class:

Page 26: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 26

public static RecordStore openRecordStore(String recordStoreName,boolean createIfNecessary, byte authMode, boolean writable) throws RecordStoreException, RecordStoreFullException,RecordStoreNotFoundException Only a MIDlet belonging to the suite that created the record store can change its authorization mode and writable flag.

Remove or replace Perticular Record To remove a particular record

void deleteRecord(int recordId) To replace a particular data

public void setRecord(int recordId, byte[] newData, int offset, int numBytes) throws RecordStoreNotOpenException,InvalidRecordIDException,RecordStoreException, RecordStoreFullException

For Details please visit http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/rms/RecordStore.html

RecordStore

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hello; import java.util.*; import javax.microedition.rms.*; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.rms.RecordStoreException; //import util.prefs.Preferences; public class RecordMidlet extends MIDlet //implements CommandListener { public String record=null; public String record1=null; byte[] data;

Page 27: J2me

S a p t a r s h i C h a t t e r j e e , e m a i l : s a p t a r s h i c h a t t e r j e e 1 @ g m a i l . c o m , P h 9 4 3 3 8 8 4 7 2 7

Page 27

int id; RecordStore rs; //RecordStore rs1; Form form; TextField t; public RecordMidlet() { form = new Form("my Form"); } public void exp() { try{ record = "Saptarshi Chatterjee"; rs=RecordStore.openRecordStore("sap",true); data = record.getBytes(); id = rs.addRecord(data, 0, data.length); byte[] n= rs.getRecord(id); record1=new String(n); // Here n.toString() won’t work Date date = new Date(rs.getLastModified()); // Gregorian calendar t = new TextField("Record Store", ("id:"+id+"Vrsn"+rs.getVersion()+"Mod:"+date+""+record1), 200, TextField.ANY); rs.closeRecordStore(); form.append(t); Display.getDisplay(this).setCurrent(form); } catch(Exception e){ Displayable a=new Alert(e+""); Display.getDisplay(this).setCurrent(a); } } // public void commandAction(Command c, Displayable s){} public void startApp() { exp(); } public void pauseApp() {} public void destroyApp(boolean unconditional) {notifyDestroyed();} }


Recommended