Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

Mobile Application Development Lab

LAB MANUAL

By

B.S.ANILKUMAR
Assistant Professor
Department of Information Technology
Joginapally B R Engineering College

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

J2ME Wireless Toolkit

Building and running a J2ME application at the command line is cumbersome, to say the least,
when you are creating a robust application consisting of several MIDlets. Creating your application
within an integrated development environment is more productive than developing applications by
entering commands at the command line.
There are a number of popular integrated development environments on the market designed
for developing J2ME applications. These include Borland’s JBuilder and Sun Microsystems’ Forte.
Another integrated development environment is the J2MEWireless Toolkit that is downloadable from
java.sun.com/products/j2mewtoolkit/download.html.
The J2MEWireless Toolkit is used to develop and test J2ME applications by selecting a few
buttons from a toolbar. However, the J2MEWireless Toolkit is a stripped-down integrated development
environment in that it does not include an editor, a full debugger, and other amenities found in a third-
party integrated development environment.

Building and Running a Project

Download the J2ME Wireless Toolkit from the Sun web site. The Toolkit file is a self extracting
executable file. Run this executable after downloading the file, and the installation program creates all
the directories required to run the Toolkit. The installed J2MEWireless Toolkit is placed in the WTK104
directory, although the directory might have a variation of this name depending on the version of the
Toolkit that you download.
Ktoolbar is the executable within the directory that launches the Toolkit. The main window is
displayed (see Figure 3-7) when you run ktoolbar. You’ll notice that the main window is sparse
compared with other integrated development environments.
Let’s create a new project by selecting the New Project button from the toolbar. You’ll be
prompted to enter a project name and class name. Enter Hello World as the project name and
greeting.HelloWorld as the class name, which is the name of the first MIDlet that is associated with the
project.
After selecting the Create Project button, the J2ME Wireless Toolkit automatically creates a
directory structure for the project and also creates the manifest file and JAD file. You can see and modify
attributes of these files by selecting the Settings option, which displays a dialog box containing a series
of tabs. The first tab displayed, Required contains a list of attributes that are necessary for the manifest
file and JAD file, as previously discussed in this chapter. The Optional tab contains attributes that are
common to many projects but not required to build and deploy a J2ME application.

SETTING THE PATH IN WINDOWS

Windows 2000 / 7 / 8 and Windows NT

1. Choose System from the Control Panel.


2. Select Environment or Advanced/Environment.
3. Locate the PATH environment variable.
4. Enter the directory at the end of the path. Be sure to separate entries with a semicolon.

Windows 98 and Windows 95

1. Select Start.
2. Select Run.
3. Enter sysedit.
4. Select OK.

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

5. Locate the autoexec.bat dialog box.


6. Add the directory to the PATH environment variable.

OBJECTIVE

In this lab, a student is expected to design, implement, document and present a mobile client/server
system using standard Java and Java 2 Micro Edition (J2ME) platform. Specifically it is required to
design and implement a system that consists mainly of a mobile client and a Proxy Server, Mobile Client
will be written in J2ME, MIDP 2.0, while PS will be written in standard Java. It is necessary to use a
mobile phone emulator to develop and demonstrate the experiments.

Once after successful installation of Java and the tool kit , compile this program and run the
following program in the toolkit.

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

EXPERIMENT-1: HELLO WORLD MIDLET

1.1 OBJECTIVE

To execute a simple J2ME application that displays ‘HelloWorld’ in the emulator.

1.2 RESOURCES:

JDK(any version), Sun Java (TM) Wireless Toolkit 2.5.2_01 for CLDC
Or
JDK(any version), NetBeans IDE 7.0.1 / 7.0.3 / 7.2

1.3 PROGRAM SOURCE CODE

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class HelloMidlet extends MIDlet
{
public HelloMidlet()
{
}
public void startApp()
{
Display.getDisplay(this).setCurrent(new TextBox("","Hello Anvesh RK", 20, 0));
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
}

1.4 PROCEDURE

Steps to run this program in toolkit:

1. Start -> All Programs -> Sun Java Tool Kit -> Wireless Tool Kit
2. Click New Project – Enter Project Name -> Enter Class Name -> Click on Create Project.
3. Choose appropriate API Selection and Configuration.
4. Place Java Source file in WTK 2.1 / WTK 2.2\apps\projectname\src..
5. Build the Project
6. Finally Run the Project (Application executes if there are no errors)

1.5 PRE LAB QUESTIONS

1. What is J2ME?
2. What is the environment we use for development for Mobile application?
3. How many profiles do J2ME consists of ?
4. Expand “lcdui”?

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

5. Describe about Midlet?

1.6 LAB ASSIGNMENT

1. Write a J2ME program to display your name and branch on the emulator screen?
2. Implement a J2ME application which displays the real number from 1-10 vertically on the
emulator screen ?
3. Create a manifest file for Hello world program?
4. Write a sample JAD file?
5. Implement a MIDlet suite program?

1.7 POST LAB QUESTIONS

1. What is an emulator in the J2ME applications?


2. What is the normal size required to store a String of 20 characters on the emulator screen?
3. What type of interpreter is used in these J2ME applications to run the programs?
4. Give the structure of a J2ME program?
5. What is CDC?

1.8 OUTPUT:

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

EXPERIMENT-2 (a) : WORKING WITH J2ME FEATURES

2(a).1 OBJECTIVE

To Create a program which creates to the following kind of


menu *cut
*copy
*paste
*delete
*select all
*unselect all

2(a).2 DESCRIPTION :

Working with J2ME Features: Say, creating a Hello World program Experiment with the most basic features
and mobile application interaction concepts (lists, text boxes, buttons, radio boxes, soft buttons, graphics, etc)

2(a).3 RESOURCES

JDK(any version), Sun Java (TM) Wireless Toolkit 2.5.2_01 for CLDC
Or
JDK(any version), NetBeans IDE 7.0.1 / 7.0.3 / 7.2

2(a).4 PROGRAM SOURCE CODE:

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class MenuCreation extends MIDlet implements CommandListener
{
public ChoiceGroup ch;
public Form form;
public Display display;
public Command cmd;
public StringItem st;
public MenuCreation()
{
display=Display.getDisplay(this);
ch=new ChoiceGroup("Edit",Choice.EXCLUSIVE);
ch.append("cut",null);
ch.append("copy",null);
ch.append("paste",null);
ch.append("delete",null);
ch.append("select all",null);
ch.append("unselect all",null);
ch.setSelectedIndex(1, true);
cmd=new Command("Select list
item",Command.OK,1); form=new Form("");
form.append(ch);
form.addCommand(cmd);
form.setCommandListener(this);
st=new StringItem("","");

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command command,Displayable displayable)
{
if(command==cmd)
{
st.setText("");
st.setText("Mr. Anvesh RK, your selected option is
"+ch.getString(ch.getSelectedIndex()));
form.append(st);
}
}
}

2(a).5 PROCEDURE

Steps to run this program in toolkit:

1. Start -> All Programs -> Sun Java Tool Kit -> Wireless Tool Kit
2. Click New Project – Enter Project Name -> Enter Class Name -> Click on Create Project.
3. Choose appropriate API Selection and Configuration.
4. Place Java Source file in WTK 2.1 / WTK 2.2\apps\projectname\src..
5. Build the Project
6. Finally Run the Project (Application executes if there are no errors)

2(a).6 PRE-LAB QUESTIONS

1. What are the various IDEs we can use for implementing J2ME applications?
2. List out the basic packages we can use for implementing the Mobile applications?
3. What is the purpose of Wireless Toolkit 2.1 / 2.2.
4. Why do we use “form” method while programming with J2ME applications?

2(a).7 LAB ASSIGNMENT

1. Implement a J2ME application which creates a list of input & output devices with various
headings?
2. Create an application of a menu list which displays the selected item list following by your name?
3. Write a program to implement a midlet suite for displaying two different midlets which uses the
common package?
4. Write a J2ME program which reads a User defined value from a JAD file?

2(a).8 POST-LAB QUESTIONS

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

1. What is the purpose of JAD file in calling a user defined values?


2. What are the basic methods we use for implementing the J2ME applications?
Explain their importance in the mobile applications?
3. What is the purpose of ch.append method in the J2ME program?
4. CommandListener plays a major role in the J2ME applications. Explain its usage?

2(a).9 OUTPUT

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

EXPERIMENT-2(b): EVENT HANDLING

2(b).1 OBJECTIVE:

To implement a J2ME application which creates a menu which has the following options
*cut - can be on/off
*copy - can be on/off
*paste - can be on/off
*delete - can be on/off
*selectall - put all 4 options on
*unselectall - put all 4 options off

2(b).2 RESOURCES

JDK(any version), Sun Java (TM) Wireless Toolkit 2.5.2_01 for CLDC
Or
JDK(any version), NetBeans IDE 7.0.1 / 7.0.3 / 7.2

2(B).3 PROGRAM SOURCE CODE

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class MenuEvents extends MIDlet implements CommandListener,ItemStateListener
{
public ChoiceGroup ch;
public ChoiceGroup
ch1; public Form form;
public Form form1;
public Display display;
public Command View;
public Command Exit;
public Command Back;
public StringItem options;
public Item item;
public MenuEvents()
{
display=Display.getDisplay(this);
form=new Form("");
form1=new Form("Selcted Options are");
ch=new ChoiceGroup("Preferences",Choice.MULTIPLE);
ch.append("cut",null);
ch.append("copy",null);
ch.append("paste",null);
ch.append("delete",null);
ch.setSelectedIndex(1, true);
form.append(ch);
ch1=new ChoiceGroup("",Choice.EXCLUSIVE);
ch1.append("select all",null);
ch1.append("unselect all",null);
ch1.setSelectedIndex(1, true);
form.append(ch1);

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

View=new Command("View",Command.OK,1);
Exit =new Command("Exit",Command.EXIT,1);
Back=new Command("Back",Command.BACK,1);
form.addCommand(View);
form.addCommand(Exit);
form1.addCommand(Back);
form.setCommandListener(this);
form1.setCommandListener(this);
form.setItemStateListener(this);
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command,Displayable displayable)
{
if(displayable==form)
{
if(command==View)
{
boolean opt[]=new boolean[ch.size()];
options=new StringItem("","");
String values="";
ch.getSelectedFlags(opt);
options.setText(""); for(int
i=0;i<opt.length;i++)
{
if(opt[i])
{
values+=ch.getString(i)+"\n";
}
}
options.setText(values);
form1.append(options);
display.setCurrent(form1);
}
else
if(command==Exit)
{
destroyApp(true);
notifyDestroyed();
}
}
else

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

if(displayable==form1)
{
if(command==Back)
{
display.setCurrent(form);
options.setText("");
}
}
}
public void itemStateChanged(Item item)
{
if(item==ch1)
{
int i=0;
int size=ch.size();
while(i<size)
{
if(ch1.getSelectedIndex()==0)
ch.setSelectedIndex(i, true);
else
ch.setSelectedIndex(i, false);
i++;
}
}
}
}

2(b).4 PROCEDURE

Steps to run this program in toolkit:

1. Start -> All Programs -> Sun Java Tool Kit -> Wireless Tool Kit
2. Click New Project – Enter Project Name -> Enter Class Name -> Click on Create Project.
3. Choose appropriate API Selection and Configuration.
4. Place Java Source file in WTK 2.1 / WTK 2.2\apps\projectname\src..
5. Build the Project
6. Finally Run the Project (Application executes if there are no errors)

2(B).5 PRE-LAB QUESTIONS

1. Explain the role of Display.class in the J2ME applications?


2. How the instances of the classes are derived?
3. Why we use setCurrent() method in the Mobile applications?
4. List out the basic command types which appear on the emulator screen?

2(B).5 LAB ASSIGNMENT


1. Implement a J2ME application using the Display class to determine whether the screen is capable of

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

displaying color?
2. Write a J2ME program for Online help routine using Command objects?
3. Write a J2ME application for Selecting an option from a ChoiceGroup object

2(B).6 POST-LAB QUESTIONS


1. Explain the way of running a midlet program by using command line?
2. List out various methods used under Item Class?
3. How to Throwing a MIDlet StateChangeException

2(B).7 OUTPUT

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

EXPERIMENT 2(c): INPUT CHECKING

2(c).1 OBJECTIVE

To implement a MIDP application which examine, that a phone number, which a user has entered in
given format.
*Area code should be one of the following : 040, 041, 050, 0400,
044* *There should 6-8 numbers in telephone number (+area code)

2(c).2 RESOURCES

JDK(any version), Sun Java (TM) Wireless Toolkit 2.5.2_01 for CLDC
Or
JDK(any version), NetBeans IDE 7.0.1 / 7.0.3 / 7.2

2(c).3 PROGRAM SOURCE CODE

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class InputChecking extends MIDlet implements CommandListener
{
public Form form1; public
TextField textfield1;
public Command exitCommand;
public Command okCommand;
public StringItem st;
public Display display;
public InputChecking()
{
display=Display.getDisplay(this);
form1=new Form("Insert the Phone number");
exitCommand=new Command("Exit",Command.EXIT,1);
okCommand=new Command("Ok",Command.OK,1);
st=new StringItem("Phone Number is ","");
textfield1=new TextField("Phone;","",30,TextField.ANY);
form1.append(textfield1);
form1.addCommand(okCommand);
form1.addCommand(exitCommand);
form1.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form1);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command cmd,Displayable displayable)
{
if(cmd==exitCommand)

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

notifyDestroyed();
else if(cmd==okCommand)
{
String s=textfield1.getString();
s=s.replace(' ', '.');
int len=s.length();
int i=0;
int c=0;
String s1="";
while(i<len)
{
if(s.charAt(i)=='.')
{
if(c==0)
{
if(s1.equals("040") || s1.equals("041") ||
s1.equals("050")
|| s1.equals("0400") || s1.equals("044"))
{
c++;
s1="";
}
}
if(c==1)
{
if(s1.length()-1==3)
{
c++;
s1="";
}
}
}
s1=s1+s.charAt(i);
i++;
}
if(s1.length()-1==3 || s1.length()-1==4 || s1.length()-1==5)
c++;
if(c==3)
st.setText("OK");
else
{
st.setText("wrong\n Phone Number Format is xxx xxx xxxx\nArea code
must be 040|050|041|0400|044");
}
form1.append(st);
}
}
}
2(c).4 PROCEDURE

Steps to run this program in toolkit:

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

1. Start -> All Programs -> Sun Java Tool Kit -> Wireless Tool Kit
2. Click New Project – Enter Project Name -> Enter Class Name -> Click on Create Project.
3. Choose appropriate API Selection and Configuration.
4. Place Java Source file in WTK 2.1 / WTK 2.2\apps\projectname\src..
5. Build the Project
6. Finally Run the Project (Application executes if there are no errors)

2(c).5 PRE-LAB QUESTIONS

1. List out various methods used in javax.microedition.lcdui.Display Class?


2. What are High level displays and low level displays?
3. Notify various Predefined AlertTypes for the Alert Object?
4. What is a PDA?

2(c).6 LAB ASSIGNMENTS

1. Implement a Midlet application for Throwing a MIDletState-Change-Exception indestroyApp()?


2. Write a J2ME program for validating Strings as predefined in the source code?
3. Implement a J2ME program for Displaying a modal alert dialog box when an exception is thrown?
4. Write a J2ME program to Creating a form with items

2(c).7 POST –LAB QUESTIONS


1. Differentiate between Screens and Canvas?
2. Give generic syntax for the methods used under ChoiceGroup class?
3. Compare between exclusive instance and multiple instance?
4. What is the role of getString() method in the checkbox?

2(c).8 INPUT

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

OUTPUT

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

EXPERIMENT-3(a): THREADS & HIGH LEVEL USER INTERFACE

3(a).1 OBJECTIVE

To implement a MIDP application which creates a slide show which has three slides, which includes only text.
Program should change to the new slide after 5 seconds. After the third slide program returns to the first slide.

3(a).2 RESOURCES

JDK(any version), Sun Java (TM) Wireless Toolkit 2.5.2_01 for CLDC
Or
JDK(any version), NetBeans IDE 7.0.1 / 7.0.3 / 7.2

3(a).3 PROGRAM SOURCE CODE

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class SlideShow extends MIDlet implements CommandListener


{
public Form slide1;
public Form slide2;
public Form slide3;
public Command Exit;
public Display display;
public SlideShow()
{
display=Display.getDisplay(this);
Exit=new Command("Exit",Command.EXIT,1);
slide1=new Form("Slide1");
slide1.append("This is Slide number 1");
slide1.addCommand(Exit);
slide2=new Form("Slide2");
slide2.append("This is Slide number
2"); slide2.addCommand(Exit);
slide3=new Form("Slide3");
slide3.append("This is Slide number
3"); slide3.addCommand(Exit);
slide1.setCommandListener(this);
slide2.setCommandListener(this);
slide3.setCommandListener(this);
}
public void startApp()
{
Thread runner = new Thread(new ThreadRunner(display,slide1,slide2,slide3));
runner.start();
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

{
}
public void commandAction(Command command,Displayable displayable)
{
if(displayable==slide1)
{
if(command==Exit) notifyDestroyed();
}
else if(displayable==slide2)
{
if(command==Exit) notifyDestroyed();
}
else if(displayable==slide3)
{
if(command==Exit)
notifyDestroyed();
}
}
}
class ThreadRunner implements Runnable
{
Display display;
public int c=0;
public Form slide1;
public Form slide2;
public Form slide3;
public ThreadRunner(Display display,Form slide1,Form slide2,Form slide3)
{
this.display = display;
this.slide1=slide1;
this.slide2=slide2;
this.slide3=slide3;
}
public void run()
{
while(true)
{
c++;
if(c==1)
display.setCurrent(slide1);
else if(c==2)
display.setCurrent(slide2);
else if(c==3)
display.setCurrent(slide3);
else if(c==4) c=0;
try
{
Thread.sleep(1500);
}
catch(Exception ex)

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

{
}
}
}
}

3(a).4 PROCEDURE

Steps to run this program in toolkit:

1. Start -> All Programs -> Sun Java Tool Kit -> Wireless Tool Kit
2. Click New Project – Enter Project Name -> Enter Class Name -> Click on Create Project.
3. Choose appropriate API Selection and Configuration.
4. Place Java Source file in WTK 2.1 / WTK 2.2\apps\projectname\src..
5. Build the Project
6. Finally Run the Project (Application executes if there are no errors)

3(a).5 PRE-LAB QUESTIONS

1. What are the instances of DateField class?


2. How to create an instance of the Gauge class?
3. List out various of javax.microedition.lcdui.Command Class?
4. On what basis the radio signal travels?

3(a).6 LAB ASSIGNMENT

1. Implement a J2MEapplication to Creating and accessing check boxes?


2. Write a J2ME program for implementing 10 slides of different text with a delay of 3 seconds of each slide?
3. Write a J2ME application for Displaying the system’s date?
4. Implement a presentation which displays different text upto last slide, and stop slideshow?

3(a).7 POST-LAB QUESTIONS

1. How to calculate pulses in sleep method?


2. Why should we use TextField class used for inputting text into an application?
3. What is a non-interactive gauge?
4. How the rating is given to an interactive gauge based on the methods used in the J2ME application?

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

3(a).8 OUTPUT

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

EXPERIMENT-3(b): HIGH-LEVEL USER INTERFACE

3(b).1 OBJECTIVE

To implement a MIDP application, which show to the user 5 quiz questions. All questions have 4 possible
options and one right opinion exactly. This application counts and shown to the user how many right answers
were right and shows them to user.

3(b).2 RESOURCES

JDK(any version), Sun Java (TM) Wireless Toolkit 2.5.2_01 for CLDC
Or
JDK(any version), NetBeans IDE 7.0.1 / 7.0.3 / 7.2

3(b).3 PROGRAM SOURCE CODE

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.io.*;
public class QuizMidlet extends MIDlet implements CommandListener
{
public Form form1; public
Form form2; public Form
form3; public Form
form4; public Form
form5; public Form
form6; public Form
form7; public
ChoiceGroup ch1; public
ChoiceGroup ch2; public
ChoiceGroup ch3;; public
ChoiceGroup ch4;; public
ChoiceGroup ch5;;
public Command nextCommand;
public Command backCommand;
public Command MenuCommand;
public Command OkCommand;
public Command ExitCommand;
public Command sCommand;
public Display display;
public StringItem st;
public TextField textfield;
public int count;
public RecordStore recordstore=null;
public RecordEnumeration re=null;
public Alert alert;
public Compare comp;
public StringItem st1;
public QuizMidlet()
{

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

count=0;
display=Display.getDisplay(this);
nextCommand=new Command("Next",Command.OK,1);
backCommand=new Command("Back",Command.BACK,1);
OkCommand=new Command("Save",Command.SCREEN,1);
ExitCommand=new Command("Exit",Command.SCREEN,1);
sCommand=new Command("TopScores",Command.SCREEN,1);
st=new StringItem("TotalPoints","0");
st1=new StringItem("","");
textfield=new TextField("EnterName","",20,TextField.ANY);
form1=new Form("J2ME Stands for");
form2=new Form("a+b=");
form3=new Form("5*5");
form4=new Form("Who is AP CM");
form5=new Form("How many Districts in
AP"); form6=new Form("Score");
form7=new Form("Top Scoreers");
ch1=new ChoiceGroup("",Choice.EXCLUSIVE);
ch1.append("Java 2 Mobile Edition", null);
ch1.append("Java 2 Macro Edition", null);
ch1.append("Java 2 Micro Edition", null);
ch1.append("Java 2 Music Edition", null);
form1.append(ch1);
form1.addCommand(nextCommand);
form1.setCommandListener(this);
ch2=new ChoiceGroup("",Choice.EXCLUSIVE);
ch2.append("b+a", null);
ch2.append("b*a", null);
ch2.append("b/a", null);
ch2.append("b-a", null);
form2.append(ch2);
form2.addCommand(nextCommand);
form2.addCommand(backCommand);
form2.setCommandListener(this);
ch3=new ChoiceGroup("",Choice.EXCLUSIVE);
ch3.append("20", null);
ch3.append("30", null);
ch3.append("10", null);
ch3.append("25", null);
form3.append(ch3);
form3.addCommand(nextCommand);
form3.addCommand(backCommand);
form3.setCommandListener(this);
ch4=new ChoiceGroup("",Choice.EXCLUSIVE);
ch4.append("Rosiah", null);
ch4.append("Jagan", null);
ch4.append("ChandaBabu", null);
ch4.append("Kiran", null);
form4.append(ch4);
form4.addCommand(nextCommand);

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

form4.addCommand(backCommand);
form4.setCommandListener(this);
ch5=new ChoiceGroup("",Choice.EXCLUSIVE);
ch5.append("8", null);
ch5.append("4", null);
ch5.append("11", null);
ch5.append("23", null);
form5.append(ch5);
form5.addCommand(backCommand);
form5.addCommand(nextCommand);
form5.setCommandListener(this);
form6.addCommand(OkCommand);
form6.addCommand(ExitCommand);
form6.addCommand(sCommand);
form6.setCommandListener(this);
form7.addCommand(backCommand);
form7.setCommandListener(this); try
{
recordstore=RecordStore.openRecordStore("Quiz", true);
}
catch(Exception ex)
{
}
}
public void startApp()
{
display.setCurrent(form1);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command cmd,Displayable displayable)
{
if(displayable==form1)
{
if(cmd==nextCommand)
display.setCurrent(form2);
}
else if(displayable==form2)
{
if(cmd==nextCommand)
display.setCurrent(form3);
else if(cmd==backCommand)
display.setCurrent(form1);
}
else if(displayable==form3)

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

{
if(cmd==nextCommand)
display.setCurrent(form4);
else if(cmd==backCommand)
display.setCurrent(form2);
}
else if(displayable==form4)
{
if(cmd==nextCommand)
display.setCurrent(form5);
else if(cmd==backCommand)
display.setCurrent(form3);
}
else if(displayable==form5)
{
if(cmd==nextCommand)
{
if(ch1.getSelectedIndex()==2)
count++;
if(ch2.getSelectedIndex()==0)
count++;
if(ch3.getSelectedIndex()==3)
count++;
if(ch4.getSelectedIndex()==3)
count++;
if(ch5.getSelectedIndex()==3)
count++;
st.setText(String.valueOf(count));
form6.append(st);
form6.append(textfield);
display.setCurrent(form6);
}
else if(cmd==backCommand)
display.setCurrent(form4);
}
else if(displayable==form6)
{
if(cmd==OkCommand)
{
try
{
String Pname=textfield.getString();
int Points=Integer.parseInt(st.getText());
byte[] bytes;
ByteArrayOutputStream ostream=new
ByteArrayOutputStream();
DataOutputStream dstream =new
DataOutputStream(ostream); dstream.writeUTF(Pname);
dstream.writeInt(Points);
dstream.flush();

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

bytes=ostream.toByteArray();
recordstore.addRecord(bytes, 0,bytes.length );
ostream.reset();
ostream.close();
dstream.close();
alert =new Alert("Message","Saved",null,AlertType.INFO);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
catch(Exception ex)
{
alert =new Alert("Message",ex.toString(),null,AlertType.INFO);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
else if(cmd==ExitCommand)
{
try
{
recordstore.closeRecordStore();
notifyDestroyed();
}
catch(Exception ex) { }
}
else if(cmd==sCommand)
{
try
{
byte[] bytes=new byte[300];
ByteArrayInputStream bstream=new
ByteArrayInputStream(bytes); DataInputStream dstream=new
DataInputStream(bstream); StringBuffer sb=new StringBuffer();
comp=new Compare();
re=recordstore.enumerateRecords(null, comp,false);
st1.setText(""); while(re.hasNextElement())
{
recordstore.getRecord(re.nextRecordId(), bytes, 0);
sb.append(dstream.readUTF()+"|"+dstream.readInt());
sb.append("\n");
dstream.reset();
}
bstream.close();
dstream.close();
st1.setText(sb.toString());
form7.append(st1);
}
catch(Exception ex)
{
alert =new Alert("Msg",ex.toString(),null,AlertType.INFO);

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
display.setCurrent(form7);
}
}
else if(displayable==form7)
{
if(cmd==backCommand)
display.setCurrent(form6);
}
}
}
class Compare implements RecordComparator
{
public byte[] bytedata=new byte[300]; public
ByteArrayInputStream bstream=null; public
DataInputStream dstream=null; public int
compare(byte[] r1,byte[] r2)
{
int r1int,r2int;
int or=0;
try
{
int maxlen=Math.max(r1.length, r2.length);
if(maxlen>bytedata.length)
{
bytedata=new byte[maxlen];
}
bstream=new ByteArrayInputStream(r1);
dstream=new DataInputStream(bstream);
dstream.readUTF();
r1int=dstream.readInt();
bstream=new ByteArrayInputStream(r2);
dstream=new DataInputStream(bstream);
dstream.readUTF();
r2int=dstream.readInt();
if(r1int==r2int)
{
or= RecordComparator.EQUIVALENT;
}
else if(r1int>r2int)
{
or= RecordComparator.PRECEDES;
}
else if(r1int<r2int)
{
or= RecordComparator.FOLLOWS;
}
return or;

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

}
catch(Exception ex)
{
return RecordComparator.EQUIVALENT;
}
}
public void compareClose()
{
try
{
if(bstream!=null)
{
bstream.close();
}
if(dstream!=null)
{
dstream.close();
}
}
catch(Exception ex) { }
}
}

3(b).4 PROCEDURE

Steps to run this program in toolkit:

1. Start -> All Programs -> Sun Java Tool Kit -> Wireless Tool Kit
2. Click New Project – Enter Project Name -> Enter Class Name -> Click on Create Project.
3. Choose appropriate API Selection and Configuration.
4. Place Java Source file in WTK 2.1 / WTK 2.2\apps\projectname\src..
5. Build the Project
6. Finally Run the Project (Application executes if there are no errors)

3(b).5 PRE-LAB QUESTIONS

1. Expand RMS?
2. What are the basic packages used for storage of data in J2ME?
3. Do the DBMS can calculate values in a table and return the result of the calculation? Explain it for
the following methods:-
(i) SUM()
(ii) AVG()
(ii) MIN()
(iv) MAX()
(v) COUNT()
3(b).6 LAB ASSIGNMENTS

1. Implement a J2ME application which creates a 10 Quiz questions with 5 options in each question.
2. Write a J2ME program to store the general data of a user(say score, name, etc.,.)
3. Implement a J2ME application for an interactive gauge?
4. Implement the StringItem class which includes Question and Answer in the application?
5. Develop a J2ME application to Write and Read a record?

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

3(b).7 POST-LAB QUESTIONS

1. What is the purpose of RMS?


2. What is the purpose of “ANY” constraint in the TextField methods?
3. List out various TextField Object Constraints?
4.What are the different Compare methods used for Sorting the records?

3(b).8 INPUT

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

OUTPUT

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

EXPERIMENT-4(a): WORKING ON “DRAWING” & “IMAGES”

4(a).1 OBJECTIVE:

To implement a MIDP application which creates a slide show which has three slides, which includes
pictures at PNG format. In this application the slides will change for every 5 seconds.

4(a).2 RESOURCES

JDK(any version), Sun Java (TM) Wireless Toolkit 2.5.2_01 for CLDC
Or
JDK(any version), NetBeans IDE 7.0.1 / 7.0.3 / 7.2

4(a).3 PROGRAM SOURCE CODE:

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class imageSlideShow extends MIDlet implements CommandListener
{
public Form slide1;
public Form slide2;
public Form slide3;
public Command Exit;
public Display display;
public Image image1;
public Image image2;
public Image image3;
public ImageItem imageitem1;
public ImageItem imageitem2;
public ImageItem imageitem3;
public imageSlideShow()
{
display=Display.getDisplay(this);
try
{
image1=Image.createImage("/1.jpg");
image2=Image.createImage("/2.jpg");
image3=Image.createImage("/3.jpg");
imageitem1=new
ImageItem(null,image1,ImageItem.LAYOUT_CENTER,"image1");
imageitem2=new
ImageItem(null,image2,ImageItem.LAYOUT_CENTER,"image2");
imageitem3=new
ImageItem(null,image3,ImageItem.LAYOUT_CENTER,"image3");
}
catch(Exception ex)
{
}
Exit=new Command("Exit",Command.EXIT,1);
slide1=new Form("Slide1");

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

slide1.append(imageitem1);
slide1.addCommand(Exit);

slide2=new Form("Slide2");
slide2.append(imageitem2);
slide2.addCommand(Exit);

slide3=new Form("Slide3");
slide3.append(imageitem3);
slide3.addCommand(Exit);

slide1.setCommandListener(this);
slide2.setCommandListener(this);
slide3.setCommandListener(this);
}
public void startApp()
{
Thread runner = new Thread(new ThreadRunner(display,slide1,slide2,slide3));
runner.start();
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command,Displayable displayable)
{
if(displayable==slide1)
{
if(command==Exit)
notifyDestroyed();
}
else if(displayable==slide2)
{
if(command==Exit)
notifyDestroyed();
}
else if(displayable==slide3)
{
if(command==Exit)
notifyDestroyed();
}
}
}
class ThreadRunner implements Runnable
{
Display display;
public int c=0;
public Form slide1;

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

public Form slide2;


public Form slide3;
public ThreadRunner(Display display,Form slide1,Form slide2,Form slide3)
{
this.display = display;
this.slide1=slide1;
this.slide2=slide2;
this.slide3=slide3;
}
public void run()
{
while(true)
{
c++;
if(c==1)
display.setCurrent(slide1);
else if(c==2)
display.setCurrent(slide2);
else if(c==3)
display.setCurrent(slide3);
else if(c==4)
c=0;
try
{
Thread.sleep(1500);
}
catch(Exception ex)
{
}
}
}
}

4(a).4 PROCEDURE

Steps to run this program in toolkit:

1. Start -> All Programs -> Sun Java Tool Kit -> Wireless Tool Kit
2. Click New Project – Enter Project Name -> Enter Class Name -> Click on Create Project.
3. Choose appropriate API Selection and Configuration.
4. Place Java Source file in WTK 2.1 / WTK 2.2\apps\projectname\src..
5. Build the Project
6. Finally Run the Project (Application executes if there are no errors)

4(a).5 PRE-LAB QUESTIONS

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

1. What is an immutable image?


2. When do we call getSelectedFlag() method.
3. How to create an Instance of a TextBox Class?
4. What is the instance of a Ticker class?

4(a).6 LAB ASSIGNMENTS

1. Write a J2ME application which implements a Ticker in the MIDlet emulator?


2. Implement a J2ME application to insert an image, and display in the emulator screen?
3. Develop a J2ME program which includes text and images in the slide show, and displays every
slide in 5 seconds
4. Develop a J2ME program for Interacting with an instance of a TextBox class

4(a).7 POST-LAB QUESTIONS

1. What is the purpose of :-


(a) getLabel() method,
(b) setLabel method,
(c) getAltText() method, and
(d) setAltText()method.
2. How to create an instance of a List class?
3. Differentiate between TextBox class and TextField class?

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

4(a).8 OUTPUT:

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

EXPERIMENT-4(b): BAR GRAPH


4(b).1 OBJECTIVE

To implement a MIDP application which creates a Bar graph to the display, where the data values are given
at int[] array.

4(b).2 RESOURCES

JDK(any version), Sun Java (TM) Wireless Toolkit 2.5.2_01 for CLDC
Or
JDK(any version), NetBeans IDE 7.0.1 / 7.0.3 / 7.2

4(b).3 PROGRAM SOURCE CODE

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class BarGraphMIDlet extends MIDlet implements CommandListener
{
public Form form;
public Command exitCommand;
public Command OkCommand;
public Command backCommand;
public Displayable d;
public Display display;
public TextField textfield1;
public TextField textfield2;
public TextField textfield3;
public TextField textfield4;
public TextField textfield5;
public BarGraphMIDlet()
{
display=Display.getDisplay(this);
form=new Form("BarGraph");
textfield1=new TextField("Value1:-","",30,TextField.ANY);
textfield2=new TextField("Value2:-","",30,TextField.ANY);
textfield3=new TextField("Value3:-","",30,TextField.ANY);
textfield4=new TextField("Value4:-","",30,TextField.ANY);
textfield5=new TextField("Value5:-","",30,TextField.ANY);
form.append(textfield1);
form.append(textfield2);
form.append(textfield3);
form.append(textfield4);
form.append(textfield5);
OkCommand=new Command("Ok",Command.OK,1);
exitCommand=new Command("Exit",Command.EXIT,1);
backCommand=new Command("Back",Command.BACK,1);
form.addCommand(OkCommand);
form.addCommand(exitCommand);
form.setCommandListener(this);
}

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

public void startApp()


{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command,Displayable displayable)
{
if(displayable==form)
{
if(command==OkCommand)
{
int[] data=new int[5];
data[0]=Integer.parseInt(textfield1.getString());
data[1]=Integer.parseInt(textfield2.getString());
data[2]=Integer.parseInt(textfield3.getString());
data[3]=Integer.parseInt(textfield4.getString());
data[4]=Integer.parseInt(textfield5.getString());
d=new BarCanvas(data); d.addCommand(backCommand);
d.setCommandListener(this); display.setCurrent(d);
}
else if(command==exitCommand) notifyDestroyed();
}
else if(displayable==d)
{
if(command==backCommand)
display.setCurrent(form);
}
}
}
class BarCanvas extends Canvas
{
int[] data;
public int x;
public int y;
public int y1;
public int h;
public BarCanvas(int[] data)
{
this.data=data;
x=10;
}
public void paint(Graphics g)
{
g.setColor(255, 255, 255);
g.fillRect(0, 0, this.getWidth(), this.getHeight());

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

g.setColor(255, 125, 100);


int i=0; y1=data[0]; h=200;
while(i<data.length)
{
y=data[i];
h=200+y1-y;
g.fillRect(x, y,25 , h);
x+=30;
i++;
}
}
}

4(b).4 PROCEDURE

Steps to run this program in toolkit:

1. Start -> All Programs -> Sun Java Tool Kit -> Wireless Tool Kit
2. Click New Project – Enter Project Name -> Enter Class Name -> Click on Create Project.
3. Choose appropriate API Selection and Configuration.
4. Place Java Source file in WTK 2.1 / WTK 2.2\apps\projectname\src..
5. Build the Project
6. Finally Run the Project (Application executes if there are no errors)

4(b).5 PRE-LAB QUESTIONS

1. Define Canvas?
2. Explain about
(a) showNotify() method
(b) hideNotify() method
3. What is meant by GraphicContext?
4. How can we draw an image on the canvas?

4(b).6 LAB ASSIGNMENT

1. Write a J2ME application for Capturing and processing game actions?2


2. Implement a program for drawing a rectangle on the canvas?
3. Develop a J2ME application for drawing an Arc on the emulator?
4. Implement a J2ME Drawing text on the canvas

4(b).7 POST-LAB QUESTIONS

1. Differentiate between paint() method and repaint() method?


2. What is the instance for drawing an Arc on the canvas?
3. List out some of the font constants?

4(b).8 OUTPUT

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

EXPERIMENT-4(c): PIE GRAPH

4(c).1 OBJECTIVE:

To implement a MIDP application which draws a Pie graph to the display. Data values can be given
at int[] array. You can enter four data (integer) values to the input text field.

4(c).2 RESOURCES

JDK(any version), Sun Java (TM) Wireless Toolkit 2.5.2_01 for CLDC
Or
JDK(any version), NetBeans IDE 7.0.1 / 7.0.3 / 7.2

4(c).3 PROGRAM SOURCE CODE

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
public class PieChartMIDlet extends MIDlet implements CommandListener
{
public Form form;
public Command exitCommand;
public Command OkCommand;
public Display display;
public TextField textfield1;
public TextField textfield2;
public TextField textfield3;
public TextField textfield4;
public TextField textfield5;
public Displayable d;
public void startApp()
{
display = Display.getDisplay(this);
form=new Form("Draw Pie");
textfield1=new TextField("Value1:-","",30,TextField.ANY);
textfield2=new TextField("Value2:-","",30,TextField.ANY);
textfield3=new TextField("Value3:-","",30,TextField.ANY);
textfield4=new TextField("Value4:-","",30,TextField.ANY);
textfield5=new TextField("Value5:-","",30,TextField.ANY);
form.append(textfield1);
form.append(textfield2);
form.append(textfield3);
form.append(textfield4);
form.append(textfield5);
exitCommand = new Command("exit", Command.EXIT, 1);
OkCommand=new Command("Ok",Command.OK,1);
form.addCommand(OkCommand);
form.addCommand(exitCommand);
form.setCommandListener(this);
display.setCurrent(form);
}

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

public void
pauseApp() { }
public void destroyApp(boolean
unconditional) { }
public void commandAction(Command c, Displayable s)
{
if(s==form)
{
if(c==exitCommand)
notifyDestroyed();
else if(c==OkCommand)
{
int[] data = new int[5];
data[0]=Integer.parseInt(textfield1.getString());
data[1]=Integer.parseInt(textfield2.getString());
data[2]=Integer.parseInt(textfield3.getString());
data[3]=Integer.parseInt(textfield4.getString());
data[4]=Integer.parseInt(textfield5.getString());
d = new PieChartCanvas(data);
d.addCommand(exitCommand);
d.setCommandListener(this);
display.setCurrent(d);
}
}
else if(s==d)
{
if(c==exitCommand)
display.setCurrent(form);
}
}
}class PieChartCanvas extends Canvas
{
int[] data;
int colors[] = { 0xFF0000, 0xA9E969, 0x00FFFF, 0xC675EC, 0x008800, 0x00C400
}; public PieChartCanvas(int[] data)
{
this.data = data;
}
public void paint(Graphics g)
{
int width = this.getWidth();
int height = this.getHeight();
g.setColor(255, 255, 255);
g.fillRect(0, 0, width,
height); int sum = 0;
for (int i = 0; i < data.length; i++)
{
sum += data[i];
}
int deltaAngle = 360 * 100 / sum / 100;

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

int x = 4; int y = 4; int diameter;


if (width > height)
diameter = height - y * 2;
else diameter = width - x *
2; int startAngle = 0;
for (int i = 0; i < data.length; i++)
{
g.setColor(colors[i]);
g.fillArc(x, y, diameter, diameter, startAngle, deltaAngle * data[i]);
startAngle += deltaAngle * data[i];
}
}
}

4(c).4 PROCEDURE

Steps to run this program in toolkit:

1. Start -> All Programs -> Sun Java Tool Kit -> Wireless Tool Kit
2. Click New Project – Enter Project Name -> Enter Class Name -> Click on Create Project.
3. Choose appropriate API Selection and Configuration.
4. Place Java Source file in WTK 2.1 / WTK 2.2\apps\projectname\src..
5. Build the Project
6. Finally Run the Project (Application executes if there are no errors)

4(c).5 PRE-LAB QUESTIONS

1. Give an instance for creating an Image?


2. What is the purpose of using translated coordinates?
3. Give out various methods used in Record Storage Management?

4(c).6 LAB ASSIGNMENT

1. Implement a J2ME program from creating a clipping region?


2. Develop a J2ME program for drawing a Pie Diagram which consists of 10 equal parts?
3. Implement a J2ME program for Create, close, and remove a record store.
4. Write a J2ME program for creating a filled in arc?

4(c).7 POST-LAB QUESTIONS

1. What is meant by a Clipping Region?


2. Write the instance used for drawing a pie chart?
3. What is an Animation. How is Animation can be imported in the emulator?
4. What is an index in the table?

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

4(c).8 OUTPUT

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

EXPERIMENT-5: DEVELOPING NETWORKED APPLICATIONS

5.1 OBJECTIVE

To Create a Simple Client-Server Application, Create, compile and run a basic UDP-based client-
server application.

5.2 RESOURCES

JDK(any version), Sun Java (TM) Wireless Toolkit 2.5.2_01 for CLDC
Or
JDK(any version), NetBeans IDE 7.0.1 / 7.0.3 / 7.2

5.3 PROGRAM SOURCE CODE FOR DATAGRAM SERVER

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
public class DatagramServer extends MIDlet implements CommandListener
{
public Form form1;
public Form form2;
public Command startCommand;
public Command refreshCommand;
public Command exitCommand;
public Display display;
public StringItem st;
public DatagramServer()
{
display=Display.getDisplay(this);
startCommand=new Command("Start",Command.OK,1);
refreshCommand=new Command("Refresh",Command.OK,1);
exitCommand=new Command("Exit",Command.EXIT,1);
st=new StringItem(" "," ");
form1 =new Form("DataGramserver");
form2=new Form("Ready to receive Messages");
form1.addCommand(startCommand);
form1.setCommandListener(this);
form2.addCommand(refreshCommand);
form2.addCommand(exitCommand);
form2.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form1);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

{
}
public void commandAction(Command cmd,Displayable displayable)
{
if(displayable==form1)
{
if(cmd==startCommand)
{
try
{
DatagramConnection dgc = (DatagramConnection)
Connector.open("datagram://:9001");
try
{
int size = 100;
Datagram datagram = dgc.newDatagram(size);
dgc.receive(datagram);
form2.append(datagram.getData().toString());
}
finally
{
dgc.close();
}
}
catch (Exception x)
{
x.printStackTrace();
}
display.setCurrent(form2);
}
}
else if(displayable==form2)
{
if(cmd==exitCommand)
{
notifyDestroyed();
}
else if(cmd==refreshCommand)
{
st.setText(" ");
}
}
}
}

5.4(a) PROCEDURE FOR DATAGRAM SERVER PROJECT

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

Creating the Datagram Server project

1. Click on Wireless Toolkit 2.5.2 under the group:All Programs→Sun Java (TM) Wireless Toolkit
2.5.2.
2. Click on 'New Project...' button.
3. Enter project name as 'DatagramServer'. Enter MIDlet name as 'DatagramServer'. Note that the
Midlet name is the same as the name of the class in the source code, which extends the MIDlet
class, otherwise the application won’t run.
4. Another window pops up where it is required to select a target platform. Select 'MIDP 1.0' from
the drop down list.
5. After clicking OK, the project is created; and the Wireless Toolkit tells that the name of the
folder where source code files are created. The path of the source code folder is displayed in the
debug output window.

Creating and Compiling the DatagramServer source files

The Wireless Toolkit does not come with an IDE by default so Use any IDE or a text editor like
Notepad.

1. Create a new text file called DatagramServer.java in the source folder of the project. The exact
path of this folder is displayed in the Wireless Toolkit window.
2. Paste contents DatagramServer.java from into the source file.

Running your Server application on the Phone simulator

1. After compiling the project successfully, click on the Run button in the Wireless Toolkit window.
2. A graphical window depicting a phone handset will appear with the name of your application
highlighted on its screen as shown below.
3. To start the application, click on the right soft-key (marked with a dot) below the ‘Launch’
command.
4. The phone simulator might ask if it is OK to run the network application. Select ‘Yes’ by clicking
on the appropriate soft-key. The server is now up and running.
5. Keep the server running during the creation, compilation and running of the Datagram Client
application.

5.3 (b). PROGRAM SOURCE CODE FOR DATAGRAM CLIENT :

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
public class DatagramClient extends MIDlet implements CommandListener
{
public Form form1;
public Display display;
public TextField textfield;
public Command sendCommand;
public DatagramClient()
{
display=Display.getDisplay(this);
form1=new Form("Datagram Client");

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

sendCommand=new Command("send",Command.OK,1);
textfield=new TextField("Enter
Text",null,30,TextField.ANY); form1.append(textfield);
form1.addCommand(sendCommand);
form1.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form1);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command cmd,Displayable d)
{
if(cmd==sendCommand)
{
try
{
DatagramConnection dgc = (DatagramConnection)
Connector.open("datagram://localhost:9001"); try
{ while(true)
{
byte[] payload = textfield.getString().getBytes();
Datagram datagram=dgc.new Datagram(payload,
payload.length);
dgc.send(datagram);
}
}
finally
{
dgc.close();
}
}
catch (Exception x)
{
x.printStackTrace();
}
}
}
}

5.4(b) PROCEDURE FOR DATAGRAM CLIENT PROJECT

Creating the DatagramClient project

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

1. Use the same instance of the Wireless Toolkit that is used for creating and compiling the
Datagram Server project.
2. Click on 'New Project...' button.
3. A new window pops up. Enter project name as 'DatagramClient'. Enter MIDlet name as
'DatagramClient'. Note that the Midlet name is the same as the name of the class in the source
code, which extends the MIDlet class.
4. Another window pops up where one has to select a target platform. Select 'MIDP 1.0' from the
drop down list.
5. After clicking OK, the project is created and the Wireless Toolkit tells where to place the source
code files. The path of the source code folder is displayed in the debug output window as
explained before.

Creating and Compiling the DatagramClient source files

1. Create a new text file called DatagramClient.java in the source folder of the project.
2. Paste contents DatagramClient.java into the source file.
3. Then click on the Build button in the Wireless Tool kit window. If the compilation is OK, it will
say Build Complete in the window's debug output window, otherwise it will show the errors.

Note : In the source code, use the System.out.println() statement to output debug information to
this window.

Running your Client application on the Phone simulator

1. After compiling the project successfully, click on the Run button in the Wireless Toolkit window.
2. A graphical window depicting a phone handset will appear with the name of the application
highlighted on its screen.
3. To start the application, click on the right soft-key (marked with a dot) below the ‘Launch’
command.
4. The phone simulator might ask if it is OK to run the network application. Select ‘Yes’ by clicking
on the appropriate soft-key. The client is now up and running.
5. When the client executes on the phone simulator, one should see a text box with the caption
'Message'. Enter any message and press the right soft-key (corresponding to Send). If the client-
server application is working properly, the screen of the server phone will display the message
sent by the client and the client screen will now display a message sent by the server in
response. The response message from the server is the original client message in reverse.
6. Try various features of the phone simulator including the different look-and feel options.

5.5 PRE-LAB QUESTIONS

1. What is meant by generic connection framework?


2. Write the syntax for the first version of the open() method in creating HTTP connection?
3. What is a session management?
4. What are the JDBC driver types?

5.6 LAB ASSIGNMENT

1. Develop a J2ME application which Uses an HttpConnection to communicate with a server.


2. Write a J2ME program for displaying a calendar?
3. Implement a J2ME application to insert & delete a row from the Record Store?

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

4. Write a program to model a J2ME application that doesn’t retrieve information from a database?
5. Implement a J2ME application for Searching a single data type records

5.7 POST-LAB QUESTIONS

1. How to open a connection that uses HTTP as the communications protocol?


2. How many CLDC connector modes are there? What arethey? Give their purpose?
3. Write the instance for downloading an image by using an HTTP Connection?
4. Give an instance for Deleting a record from the table in J2ME?

5.8 OUTPUT

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

EXPERIMENT-6: AUTHENTICATION WITH A WEB SERVER

6.1 OBJECTIVE

To implement a sample program to show how to make a SOCKET Connection from j2me phone. This
J2ME sample program shows how to how to make a SOCKET Connection from a J2ME Phone. Many a
times there is a need to connect backend HTTP server from the J2ME application. shows how to make a
SOCKET connection from the phone to port 80.

6.2 RESOURCES

JDK(any version), Sun Java (TM) Wireless Toolkit 2.5.2_01 for CLDC
Or
JDK(any version), NetBeans IDE 7.0.1 / 7.0.3 / 7.2

6.3(A) PROGRAM SOURCE CODE:

import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;

public class socket extends MIDlet


{
// StreamConnection allows bidirectional communication
private StreamConnection streamConnection = null;

// use OutputStream to send requests


private OutputStream outputStream = null;
private DataOutputStream dataOutputStream = null;

// use InputStream to receive responses from Web server


private InputStream inputStream = null;
private DataInputStream dataInputStream = null;

// specify the connect string


private String connectString = "socket://www.java-samples.com:80";

// use a StrignBuffer to store the retrieved page


contents private StringBuffer results;

// define GUI components


private Display myDisplay = null;
private Form resultScreen;
private StringItem resultField;

public socket()
{
// initializing GUI display
results = new StringBuffer();

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

myDisplay = Display.getDisplay(this);
resultScreen = new Form("Page Content:");
}
public void startApp()
{
try
{
// establish a socket connection with remote server
streamConnection = (StreamConnection) Connector.open(connectString);

// create DataOuputStream on top of the socket connection


outputStream = streamConnection.openOutputStream();
dataOutputStream = new DataOutputStream(outputStream);

// send the HTTP request


dataOutputStream.writeChars("GET /index.htm HTTP/1.0 \n");
dataOutputStream.flush();

// create DataInputStream on top of the socket connection


inputStream = streamConnection.openInputStream();
dataInputStream = new DataInputStream(inputStream);

// retrieve the contents of the requested page from Web server


int inputChar;
while ( (inputChar = dataInputStream.read()) != -1)
{
results.append((char) inputChar);
}

// display the page contents on the phone screen


resultField = new StringItem(null, results.toString());
resultScreen.append(resultField);
myDisplay.setCurrent(resultScreen);
}
catch (IOException e)
{
System.err.println("Exception caught:" + e);
}
finally
{
// free up I/O streams and close the socket
connection try
{
if (dataInputStream != null)
dataInputStream.close();
}
catch (Exception ignored)
{
}
try

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

{
if (dataOutputStream != null)
dataOutputStream.close();
}
catch (Exception ignored)
{
}
try
{
if (outputStream != null)
outputStream.close();
}
catch (Exception ignored)
{
}
try
{
if (inputStream != null)
inputStream.close();
}
catch (Exception ignored)
{
}
try
{
if (streamConnection != null)
streamConnection.close();
}
catch (Exception ignored)
{
}
}
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
}

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

6.3(B) PROGRAM SOURCE CODE FOR LOGIN TO HTTP SERVER FROM A J2ME PROGRAM

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.io.*;
import java.lang.*;
import javax.microedition.io.*;
import javax.microedition.rms.*;
import com.symbol.j2me.midlets.ascanner.BarCodeReader;

public class Login extends MIDlet implements CommandListener


{
TextField UserName=null;
TextField Location=null; Form
authForm,mainscreen;
TextBox t = null;
StringBuffer b = new StringBuffer();
private Display myDisplay = null;
private Command okCommand = new Command("OK", Command.OK, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 2);
private Command backCommand = new Command("Back", Command.BACK, 2);
private Alert alert = null;

public Login()
{
myDisplay = Display.getDisplay(this);
UserName=new TextField("Your Name","",10,TextField.ANY);
Location=new TextField("Location","",10,TextField.ANY);
authForm=new Form("Identification");
mainscreen=new Form("Logging IN");
mainscreen.append("Logging in....");
mainscreen.addCommand(backCommand);
authForm.append(UserName);
authForm.append(Location);
authForm.addCommand(okCommand);
authForm.addCommand(exitCommand);
authForm.setCommandListener(this);
myDisplay.setCurrent(authForm);
}
public void startApp() throws MIDletStateChangeException
{
}
public void pauseApp()
{
protected void destroyApp(boolean unconditional)throws MIDletStateChangeException
{
}
public void commandAction(Command c, Displayable d)
{

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

if ((c == okCommand) && (d == authForm))


{
if (UserName.getString().equals("") || Location.getString().equals(""))
{
alert = new Alert("Error", "You should enter Username and
Location", null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
myDisplay.setCurrent(alert);
}
else
{
//myDisplay.setCurrent(mainscreen);
login(UserName.getString(),Location.getString());
}
}
if ((c == backCommand) && (d == mainscreen))
{
myDisplay.setCurrent(authForm);
}
if ((c == exitCommand) && (d == authForm))
{
notifyDestroyed();
}
}
public void login(String UserName,String PassWord)
{
HttpConnection connection=null;
DataInputStream in=null;
String url="http://www.java-samples.com/use-your-own/urlhere.jsp";
OutputStream out=null;
try
{
connection=(HttpConnection)Connector.open(url);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("IF-Modified-Since", "2 Oct 2002
15:10:15 GMT");
connection.setRequestProperty("User-Agent","Profile/MIDP-1.0
Configuration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-
CA"); connection.setRequestProperty("Content-Length",""+
(UserName.length()+PassWord.length()));
connection.setRequestProperty("UserName",UserName);
connection.setRequestProperty("PassWord",PassWord);
out = connection.openDataOutputStream();
out.flush();
in = connection.openDataInputStream();
int ch;
while((ch = in.read()) != -1) {
b.append((char) ch);
//System.out.println((char)ch);

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

}
//t = new TextBox("Reply",b.toString(),1024,0);
mainscreen.append(b.toString());
if(in!=null) in.close(); if(out!=null)

out.close();
if(connection!=null)
connection.close();
}
catch(IOException x){}
myDisplay.setCurrent(mainscreen);
}
}

6.5 PRE-LAB QUESTIONS

1. What is a Socket?
2. Give the instance for HTTPCONNECTION
3. Write an instance to create a table in J2ME?
4. Is joining tables is possible in J2ME. How?

6.6 LAB ASSIGNMENT

1. Write a J2ME program for Writing to and reading from a socket connection.
2. Implement a J2ME application for Transmitting as a background process.
3. Implement a SOAP one-way transmission primitive using SMTP.
4. Implement a J2ME application for Implement a J2ME Creating a RowSet Listener, assuming the instance
rowset has already been created.

6.7 POST-LAB QUESTIONS

1. List out the types of HTTP Request Methods?


2. What are Cookies, how they are formed in CLDC MIDlets?
3. List out the Collective Enterprise JavaBeans server and Enterprise JavaBeans container system services?
4. How to drop a table from the database. Give its instance?
5. Give an instance for creating a table instance?

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

6.8 OUTPUT

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

EXPERIMENT-7: WEB APPLICATION USING J2ME

7.1 OBJECTIVE

To implement any of the Web application using J2ME.

7.2 RESOURCES

JDK(any version), Sun Java (TM) Wireless Toolkit 2.5.2_01 for CLDC
Or
JDK(any version), NetBeans IDE 7.0.1 / 7.0.3 / 7.2

7.3 DESCRIPTION

The following should be carried out with respect to the given set of application domains: (Assume that
the Server is connected to the well-maintained database of the given domain. Mobile Client is to be
connected to the Server and fetch the required data value/information)

• Students Marks Enquiry


• Town/City Movie Enquiry
• Railway/Road/Air (For example PNR) Enquiry/Status
• Sports (say, Cricket) Update
• Town/City Weather Update
• Public Exams (say Intermediate or SSC)/ Entrance (Say EAMCET) Results Enquiry

Divide Student into Batches and suggest them to design database according to their domains and render
information according the requests.

Install the developing tools.

 Download Java Development Kit (JDK 5.0 Update 4) and install it (run jdk-1_5_0_04-
 windows-i586-p.exe). 
 Download Java Wireless Toolkit (J2ME Wireless Toolkit 2.2) and install it (run
 j2me_wireless_toolkit-2_2-windows.exe). 
 Download Web container (Tomcat 5.0 for Java WSDP) and extract and install it (tomcat50-
jwsdp.zip). 
  Install Java Web Services Developer Pack. 
1. Download Java Web Services Developer Pack (Java WSDP 1.6).
2. Run jwsdp-1_6-windows-i586.exe.
3. Specify the JDK path (C:\Program Files\Java\jdk1.5.0_04) and the Web container
path (C:\tomcat50-jwsdp).
 Specify the environment path (C:\Program Files\Java\jdk1.5.0_04\bin;C:\Sun\jwsdp-1.6\jwsdp-
shared\bin;C:\Sun\jwsdp-1.6\apache-ant\bin). 

Prepare the J2ME Web service client and Java Web service.

  
Run KToolbar of J2ME Wireless Toolkit.
  
Create the new project (Hello).
  
Specify the Project Name (Hello).
 
Specify the MIDlet Class Name (HelloMidlet).

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

  Select the Additional APIs - Web Service Access for J2ME (JSR 172). 
  
Create the Web service directory (C:\WTK22\apps\Hello\server).
  
Create the source directory of Web service (C:\WTK22\apps\Hello\server\src\hello).

Write the property file (build.properties) for Apache Ant (a Java-based build tool) (in
C:\WTK22\apps\Hello\server) and these properties
 must be set according to your environment
 (project-root=C:/WTK22/apps/Hello/server).

Write the compilation and deployment file (build.xml) (in C:\WTK22\apps\Hello\server) for
Apache Ant and specify the project name according to your environment (project name =
"helloservice").

Create and deploy a Java Web service.

Write the Web service interface class (Hello.java) (in C:\WTK22\apps\Hello\server\src\hello).

package hello;
import java.rmi.*;
public interface Hello extends Remote
{
public String getHello(String name) throws RemoteException;
}

Write the Web service implementation class (HelloImpl.java) (in C:\WTK22\apps\Hello\server\src\hello).

package hello;
import java.rmi.RemoteException; public
class HelloImpl implements Hello
{
public String getHello(String name) throws RemoteException
{
return "Hello, " + name + "!";
}
}

 Write the associated descriptor files (all XML files) (in C:\WTK22\apps\Hello\server\src). 

  
config.xml
  
jaxrpc-ri.xml
 
web.xml

 Compile the service (Hello.java and HelloImpl.java) and generate Web services stubs/ties
(C:\WTK22\apps\Hello\server\generated) and WSDL file (C:\WTK22\apps\Hello\server\WEB-
INF\classes\helloservice.wsdl) using tools provided with the Java Web Services Developer Pack: 

ant compile 

 Deploy the web service to the Tomcat server. 



Build the web service to generate a web application archive
(C:\WTK22\apps\Hello\server\helloservice.war):

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

ant build


Remove the previously installed Web service (C:\tomcat50-
 jwsdp\webapps\helloservice.war).
If it is not 
removed before deployment, the incorrect WSDL (helloservice.wsdl) might be
 installed.


Deploy the web service to the Tomcat server (C:\tomcat50-
jwsdp\webapps\helloservice.war):


 ant deploy
 
 Verify if the Web service is correctly deployed.

  
Access http://localhost:8080/helloservice/helloservice.
 
Click http://localhost:8080/helloservice/helloservice?WSDL

If helloservice.wsdl cannot correctly displayed, check and the associated descriptor files.

Create the J2ME Web service client

 Use the generated WSDL file and the tools built into the Wireless Toolkit to generate the stubs
 and supporting code used by the MIDlet to access the Web service. 
o Specify the location of the Web service. (in C:\WTK22\apps\Hello\server\WEB-
INF\classes\helloservice.wsdl) <soap:address
 location="http://localhost:8080/helloservice/helloservice"/> 
 o Click the Project menu and select Stub Generator. 
o Specify WSDL Filename or URL (C:\WTK22\apps\Hello\server\WEB-
 INF\classes\helloservice.wsdl). 
o Specify Output Package (helloservice) and generate client stubs (in
 C:\WTK22\apps\Hello\src\helloservice). 
 Code the MIDlet (HelloMidlet.java) (in C:\WTK22\apps\Hello\src) and associated classes
using JAX-RPC to invoke the Web service and JAXP to process the SOAP message. 

7.4 PROGRAM SOURCE CODE:

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import java.util.*;
import java.rmi.RemoteException;
import helloservice.*;

public class HelloMidlet extends MIDlet implements Runnable, CommandListener


{
Hello_Stub service;
Display display;
private Form f;
private StringItem si;
private TextField tf;
private Command sendCommand = new Command("Send", Command.ITEM, 1);

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

private Command exitCommand = new Command("Exit", Command.EXIT,


1); String name = "";
public void startApp()
{
display = Display.getDisplay(this); f
= new Form("Hello Client");
tf = new TextField("Send:", "", 30, TextField.ANY); si
= new StringItem("Status:" , " ");
f.append(tf);
f.append(si);
f.addCommand(sendCommand);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command c, Displayable d)
{
if (c == sendCommand)
{
name = tf.getString();
si.setText("Message sent: " + name);
/* * Start a new thread so that the remote invocation won't block the process. */
new Thread(this).start();
}
if (c == exitCommand)
{
notifyDestroyed();
destroyApp(true);
}
}
public void run()
{
try
{
service = new Hello_Stub();
service._setProperty(Hello_Stub.SESSION_MAINTAIN_PROPERTY, new
Boolean(true));
String msg = service.getHello(name);
si.setText("Message Receive: " + msg);
}
catch (Exception exception)
{
}
}

B.S.Anilkumar, Asst.Professsor Department of IT


Mobile Application Development Lab

7.4 PROCEDURE

Steps to run this program in toolkit:

1. Start -> All Programs -> Sun Java Tool Kit -> Wireless Tool Kit
2. Click New Project – Enter Project Name -> Enter Class Name -> Click on Create Project.
3. Choose appropriate API Selection and Configuration.
4. Place Java Source file in WTK 2.1 / WTK 2.2\apps\projectname\src..
5. Build the Project
6. Finally Run the Project (Application executes if there are no errors)

7.5 PRE-LAB QUESTIONS

1. What is a File Protocol?


2. What are the Two components of Client-Tier?
3. Explain about :
(i) Types Element
(ii) Message Element
(iii) Binding Element
(iv) Service Element
4. What is an RMI in CLDC?

7.6 LAB ASSIGNMENT

1. Write a J2ME program for Retrieving information from a web server


2. Implement a J2ME application to Write to a file?
3. Give an XML code for Service Bindings?
4. Write a program model J2ME application that retrieves information from a database

7.7 POST-LAB QUESTIONS


1. Discuss the following terms:
(a) WSDL
(b) UDDI
(c) SOAP
2. Write the instance for Abstract binding?
3. Differentiate between Port Element and portType Element?
4. What are Holder Classes?

7.8 OUTPUT


 KToolbar) and run (click the Run button on KToolbar) the MIDlet on the
Build (click the Build button on
Wireless Toolkit emulator(s).

B.S.Anilkumar, Asst.Professsor Department of IT

You might also like