You are on page 1of 60

PRACTICAL No.

1
Que: Wrie a program in J2ME to perform the simple calculator operations such as
a. Addition
b. Subtraction
c. Multiplication
d. Division
Program:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Calc extends MIDlet implements CommandListener
{
Display disp;
TextField tf1,tf2,tf3;
Form form;
Command add,sub,mul,div,mod,exit;
public Calc()
{
disp=Display.getDisplay(this);
form=new Form("Addition of two nos");
tf1=new TextField("First no.","0",30,TextField.ANY);
tf2=new TextField("Second no.","0",30,TextField.ANY);
tf3=new TextField("Result","0",30,TextField.ANY);
form.append(tf1);
form.append(tf2);
form.append(tf3);
add=new Command("add",Command.SCREEN,1);
sub=new Command("subtract",Command.SCREEN,1);
mul=new Command("multiply",Command.SCREEN,1);
div=new Command("Divide",Command.SCREEN,1);
mod=new Command("modulus",Command.SCREEN,1);
exit=new Command("Exit",Command.EXIT,2);
form.addCommand(add);
form.addCommand(sub);
form.addCommand(mul);
form.addCommand(div);
form.addCommand(mod);
form.addCommand(exit);
form.setCommandListener(this);
}
public void startApp()
{

disp.setCurrent(form);
}
public void pauseApp()
{}
public void destroyApp(boolean unconditional)
{}
public void commandAction(Command c,Displayable d)
{
if(c==add)
{
int a=Integer.parseInt(tf1.getString());
int b=Integer.parseInt(tf2.getString());
int c1=a+b;
tf3.setString(String.valueOf(c1));
}
if(c==sub)
{
int a=Integer.parseInt(tf1.getString());
int b=Integer.parseInt(tf2.getString());
int c1=a-b;
tf3.setString(String.valueOf(c1));
}
if(c==mul)
{
int a=Integer.parseInt(tf1.getString());
int b=Integer.parseInt(tf2.getString());
int c1=a*b;
tf3.setString(String.valueOf(c1));
}
if(c==div)
{
int a=Integer.parseInt(tf1.getString());
int b=Integer.parseInt(tf2.getString());
if(b==0)
tf3.setString("Divisor cannot be zero");
else
{
int c1=a/b;
tf3.setString(String.valueOf(c1));
}
}
if(c==mod)
{
int a=Integer.parseInt(tf1.getString());
int b=Integer.parseInt(tf2.getString());

if(b==0)
tf3.setString("Divisor cannot be zero");
else
{
int c1=a%b;
tf3.setString(String.valueOf(c1));
}
}
if(c==exit)
{
destroyApp(false);
notifyDestroyed();
}
}
}
OUTPUT:

PRACTICAL No. 2
Que: Write a program in J2ME to create a simple Quiz which content 3 to 4
questions and also display the score.
Program:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.lang.*;
public class QuizDemo extends MIDlet implements CommandListener,
ItemStateListener
{
private Display disp;
private Form form1,form2,form3,form4;
private Command exit,next1,next2,next3,submit;
private TextBox msg;
private Item selection;
private ChoiceGroup radiobuttons,rdb2,rdb3,rdb4;
StringItem ms1,ms2,ms3,ms4;
private int defaultIndex;
private int radioButtonIndex;
int flag=0;
public QuizDemo()
{
disp=Display.getDisplay(this);
ms1=new StringItem(null,"Which following city is capital of India ?");
radiobuttons=new ChoiceGroup("Select your
answer",Choice.EXCLUSIVE);
radiobuttons.append("Bangalore",null);
radiobuttons.append("Delhi",null);
radiobuttons.append("Mumbai",null);
radiobuttons.append("Pune",null);
ms2=new StringItem(null,"Which following city is capital of Japan?
");
rdb2=new ChoiceGroup("Select your
answer",Choice.EXCLUSIVE);
rdb2.append("Ya ka nua",null);
rdb2.append("Bijieng",null);
rdb2.append("Tokiyo",null);
rdb2.append("ku do su",null);

ms3=new StringItem(null,"Which following city is capital of UK? ");


rdb3=new ChoiceGroup("Select your
answer",Choice.EXCLUSIVE);
rdb3.append("Amsterdam",null);
rdb3.append("London",null);
rdb3.append("New York",null);
rdb3.append("Mexico",null);
ms4=new StringItem(null,"Which following city is capital of Egypt?
");
rdb4=new ChoiceGroup("Select your
answer",Choice.EXCLUSIVE);
rdb4.append("Peru",null);
rdb4.append("Rome",null);
rdb4.append("Kairo",null);
rdb4.append("Sydney",null);
form1=new Form("Question 1");
form1.append(ms1);
radioButtonIndex=form1.append(radiobuttons);
form2=new Form("Question 2");
form2.append(ms2);
radioButtonIndex=form2.append(rdb2);
form3=new Form("Question 3");
form3.append(ms3);
radioButtonIndex=form3.append(rdb3);
form4=new Form("Question 4");
form4.append(ms4);
radioButtonIndex=form4.append(rdb4);
exit=new Command("Exit",Command.EXIT,1);
submit=new Command("Submit",Command.SCREEN,2);
next1=new Command("Next",Command.SCREEN,1);
next2=new Command("Next",Command.SCREEN,1);
next3=new Command("Next",Command.SCREEN,1);
msg=new TextBox("Message","Congrats",80,0);
form1.addCommand(next1);
form2.addCommand(next2);
form3.addCommand(next3);
form4.addCommand(submit);
form4.addCommand(exit);
form1.setCommandListener(this);
form2.setCommandListener(this);

form3.setCommandListener(this);
form4.setCommandListener(this);
form1.setItemStateListener(this);
form2.setItemStateListener(this);
form3.setItemStateListener(this);
form4.setItemStateListener(this);
}
public void startApp()
{
disp.setCurrent(form1);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}

public void itemStateChanged(Item item)


{
if(item==radiobuttons)
{
String
ans=(radiobuttons.getString(radiobuttons.getSelectedIndex()));
if(ans.equals("Delhi"))
{
flag++;
}
}
if(item==rdb2)
{
String ans=(rdb2.getString(rdb2.getSelectedIndex()));
if(ans.equals("Tokiyo"))
{
flag++;
}

}
if(item==rdb3)
{
String ans=(rdb3.getString(rdb3.getSelectedIndex()));
if(ans.equals("London"))
{
flag++;
}
}
if(item==rdb4)
{
String ans=(rdb4.getString(rdb4.getSelectedIndex()));
if(ans.equals("Kairo"))
{
flag++;
}
}
}
public void commandAction(Command com,Displayable disp1)
{
if(com==next1)
{
disp.setCurrent(form2);
}
if(com==next2)
{
disp.setCurrent(form3);
}
if(com==next3)
{
disp.setCurrent(form4);
}
if(com==exit)
{
destroyApp(false);
notifyDestroyed();
}
if(com==submit)
{
//disp.setCurrent(msg);
StringItem msg1=new StringItem(null,"Flag value is"+flag);
form4.append(msg1);

}
}
}

PRACTICAL No. 3
Que: Write a program in J2ME to create a currency converter and also display the
result.
Program:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Currency extends MIDlet implements CommandListener
{
Display disp;
TextField tf1,tf2;
Form form;
Command US,UK,Japan,exit;
public Currency()
{
disp=Display.getDisplay(this);
form=new Form("Conversion of Currency");
tf1=new TextField("Indian Currency","0",30,TextField.ANY);
tf2=new TextField("Foreign Currency","0",30,TextField.ANY);
form.append(tf1);
form.append(tf2);
US=new Command("US",Command.SCREEN,1);
UK=new Command("UK",Command.SCREEN,1);
Japan=new Command("Japan",Command.SCREEN,1);
exit=new Command("Exit",Command.EXIT,2);
form.addCommand(US);
form.addCommand(UK);
form.addCommand(Japan);
form.addCommand(exit);
form.setCommandListener(this);
}
public void startApp()
{
disp.setCurrent(form);
}
public void pauseApp()
{}
public void destroyApp(boolean unconditional)
{}
public void commandAction(Command c,Displayable d)
{
if(c==US)

{
float a=Float.parseFloat(tf1.getString());
float c1=a/48;
tf2.setString(String.valueOf(c1)+"Dollars");
}
if(c==UK)
{
float a=Float.parseFloat(tf1.getString());
float c1=a/85;
tf2.setString(String.valueOf(c1)+"Pounds");
}
if(c==Japan)
{
int a=Integer.parseInt(tf1.getString());
int c1=a*2;
tf2.setString(String.valueOf(c1)+"Yen");
}
if(c==exit)
{
destroyApp(false);
notifyDestroyed();
}
}
}

OUTPUT

PRACTICAL No. 4
Que: Write a program in J2ME to generate a calendar.
Program:
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import java.util.Date;
public class CalenderMIDlet extends MIDlet
{
private Form form;
private Display disp;
private DateField cal;
private static final int DATE=0;
public CalenderMIDlet()
{
cal=new DateField("Date In",DateField.DATE);
}
public void startApp()
{
disp=Display.getDisplay(this);
form=new Form("Calender");
form.append(cal);
disp.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
}

OUTPUT

PRACTICAL No. 5
Que: Write a program in J2ME to demonstrate simple animation through snake
movement
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class MySnake extends MIDlet implements CommandListener
{
DrawSnake ds;
Display dis;
public MySnake()
{
dis=Display.getDisplay(this);
ds=new DrawSnake();
}
public void startApp()
{
dis.setCurrent(ds);
}
public void commandAction(Command c,Displayable d)
{}
public void pauseApp()
{}
public void destroyApp(boolean unconditional)
{}
}
class DrawSnake extends Canvas implements Runnable, CommandListener
{
int x,y,dir;
Thread th;
Command quit;
public DrawSnake()
{
x=0;
y=0;
dir=0;
quit=new Command("QUIT",Command.SCREEN,1);

addCommand(quit);
setCommandListener(this);
th=new Thread(this);
th.start();
}
public void commandAction(Command c,Displayable d)
{
if(c==quit){}
//notifyDestroyed();
}
public void keyPressed(int cd)
{
switch(getGameAction(cd))
{
case Canvas.UP:
y-=5;
dir=1;
break;
case Canvas.DOWN:
y+=5;
dir=2;
break;
case Canvas.LEFT:
x-=5;
dir=3;
break;
case Canvas.RIGHT:
x+=5;
dir=4;
break;
}
}
public void run()
{
while(true)
{
if(dir==1)
y-=5;
else if(dir==2)
y+=5;
else if(dir==3)

x-=5;
else if(dir==4)
x+=5;
repaint();
try
{
th.sleep(500);
}
catch (Exception ee)
{
}
}
}
public void paint(Graphics g)
{
g.setColor(0x1F2F1F);
g.fillRect(x, y, 10, 10);
g.drawString("RUPAK RAUSHAN",25,25, Graphics.TOP | Graphics.LEFT);
}
}

PRACTICAL No. 6
Que: Write a program in J2ME to create a simple application with an address
book with the help of RecordStore.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
public class RecordStoreDemo extends MIDlet implements CommandListener
{
private Display disp;
private Form frm;
private Command add, exit, delete,update,retrived;
private TextField txtrecid, txtname,txttelno;
private RecordStore rs;
String recid, name, telno;
public RecordStoreDemo()
{
disp = Display.getDisplay(this);
exit = new Command("Exit",Command.SCREEN,1);
add = new Command("Add",Command.SCREEN,1);
delete = new Command("Delete",Command.SCREEN,1);
update = new Command("Update",Command.SCREEN,1);
retrived = new Command("Retrived",Command.SCREEN,1);
try
{
rs = RecordStore.openRecordStore("recorddemo", true);
}catch(Exception e)
{ e.printStackTrace();
}
txtrecid = new TextField("Record Id","" , 32, TextField.ANY);
txtname = new TextField("Name","" , 32, TextField.ANY);
txttelno = new TextField("Telephone No.","" , 32, TextField.ANY);
frm = new Form("Customer Details");
frm.append(txtrecid);
frm.append(txtname);
frm.append(txttelno);
frm.addCommand(exit);

frm.addCommand(add);
frm.addCommand(delete);
frm.addCommand(update);
frm.addCommand(retrived);
frm.setCommandListener(this);
}
public void startApp()
{
disp.setCurrent(frm);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command cmd, Displayable d)
{
if(cmd==exit)
{
destroyApp(true);
notifyDestroyed();
}
else if(cmd==add)
{
recid = txtrecid.getString();
name = txtname.getString();
telno = txttelno.getString();
String data = (recid+";"+name+";"+telno);
System.out.println(data);
byte b[] = data.getBytes();
try
{
int result = rs.addRecord(b, 0, b.length);
if(result>=1)
{
Alert a = new Alert("Add","Record Added",null,AlertType.INFO);
a.setTimeout(Alert.FOREVER);
disp.setCurrent(a);
txtrecid.setString("");
txtname.setString("");
txttelno.setString("");
}

else
{
Alert a = new Alert("Error","Record not Added: ",null,AlertType.ERROR);
a.setTimeout(Alert.FOREVER);
disp.setCurrent(a);
}
}catch(Exception e)
{
e.printStackTrace();
}
}
else if(cmd==retrived)
{
try
{
byte b[] = new byte[rs.getRecordSize(Integer.parseInt(txtrecid.getString()))];
rs.getRecord(Integer.parseInt(txtrecid.getString()),b,0);
String data = new String(b);
System.out.println(data);
recid = data.substring(0, data.indexOf(";")-1);
data = data.substring(data.indexOf(";")+1, data.length());
System.out.println(data);
name = data.substring(0,data.indexOf(";"));
telno = data.substring(data.indexOf(";")+1, data.length());
txtname.setString(name);
txttelno.setString(telno);
}catch(InvalidRecordIDException e)
{
Alert a = new Alert("Retrival Error","Record not
Found",null,AlertType.ERROR);
a.setTimeout(Alert.FOREVER);
disp.setCurrent(a);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else if(cmd==delete)
{
try
{

rs.deleteRecord(Integer.parseInt(txtrecid.getString()));
txtname.setString("");
txttelno.setString("");
txtrecid.setString("");
Alert a = new Alert("Delete","Record Deleted",null,AlertType.INFO);
a.setTimeout(Alert.FOREVER);
disp.setCurrent(a);
}catch(InvalidRecordIDException e)
{
Alert a = new Alert("Error","No Record to Delete",null,AlertType.ERROR);
a.setTimeout(Alert.FOREVER);
disp.setCurrent(a);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else if(cmd==update)
{
try
{
recid = txtrecid.getString();
name = txtname.getString();
telno = txttelno.getString();
String data = (recid+";"+name+";"+telno);
System.out.println(data);
byte b[] = data.getBytes();
rs.setRecord(Integer.parseInt(recid), b, 0, b.length);
Alert a = new Alert("Update","Record Updated",null,AlertType.INFO);
a.setTimeout(Alert.FOREVER);
disp.setCurrent(a);
txtrecid.setString("");
txtname.setString("");
txttelno.setString("");
}
catch(InvalidRecordIDException e)
{
Alert a = new Alert("Error","No Record to Update",null,AlertType.ERROR);
a.setTimeout(Alert.FOREVER);
disp.setCurrent(a);
}
catch(Exception e)
{
e.printStackTrace();

}
}
}
}
Output:

PRACTICAL No. 7
Que: Write a program in J2ME to create a simple database application with an
address book with the following operations:
a. Insert
Program:
import java.io.*;
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
public class MySQLConn extends MIDlet implements CommandListener {
private String username;
private String url = "http://localhost:8086/servlets-examples/get";
private Display display;
private Command exit = new Command("EXIT", Command.EXIT, 1);;
private Command connect = new Command("Connect",
Command.SCREEN, 1);
private Form menu;
private TextField tb1;
private TextField tb2;
DBConn db;
public MySQLConn() throws Exception {
display = Display.getDisplay(this);
}
public void startApp() {
displayMenu();
}
public void displayMenu() {
menu = new Form("Connect");
tb1 = new TextField("Please input username: ","",30,TextField.ANY);
tb2 = new TextField("Please input password:
","",30,TextField.PASSWORD);
menu.append(tb1);
menu.append(tb2);
menu.addCommand(exit);
menu.addCommand(connect);
menu.setCommandListener(this);
display.setCurrent(menu);

}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command command, Displayable screen) {
if (command == exit) {
destroyApp(false);
notifyDestroyed();
} else if (command == con) {
db = new DBConn(this);
db.start();
db.connectDb(tb1.getString(),tb2.getString());
}
}
public class DBConn implements Runnable {
MySQLConn midlet;
private Display display;
String db;
String user;
String pwd;
public DBConn(MySQLConn midlet) {
this.midlet = midlet;
display = Display.getDisplay(midlet);
}
public void start() {
Thread t = new Thread(this);
t.start();
}
public void run() {
StringBuffer sb = new StringBuffer();
try {
HttpConnection c = (HttpConnection) Connector.open(url);
c.setRequestProperty("User-Agent","Profile/MIDP-1.0,
Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);
DataOutputStream os =
(DataOutputStream)c.openDataOutputStream();
//os.writeUTF(db.trim());
os.writeUTF(user.trim());

os.writeUTF(pwd.trim());
os.flush();
os.close();
// Get the response from the servlet page.
DataInputStream is
=(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
}
showAlert(sb.toString());
is.close();
c.close();
} catch (Exception e) {
showAlert(e.getMessage());
}
}
/* This method takes input from user like db,user and pwd and pass to
servlet */
public void connectDb(String user,String pwd) {
//this.db = db;
this.user = user;
this.pwd = pwd;
}
/* Display Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
};
}
Servlet Code
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class GetConnection extends HttpServlet
{

Connection conn;
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
DataInputStream in = new
DataInputStream((InputStream)request.getInputStream());
String user = in.readUTF();
String pwd = in.readUTF();
System.out.println("received data is==>"+user+pwd);
try
{
// connect(user.toLowerCase().trim(), pwd.toLowerCase().trim());
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:Harshad");
Statement stmt = conn.createStatement();
int i = stmt.executeUpdate("insert into Login values('"+user+"','"+pwd+"')");
if(i!=0)
{
out.println("data has been inserted");
}
else
{
out.println("data is not inserted");
}
}catch(Exception e)
{ e.printStackTrace(); }

out.println("Data:"+user+pwd);
in.close();
out.close();
out.flush();
}
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
doPost(request,response);

}
/* private void connect( String user,String pwd) throws Exception {

}*/
}

PRACTICAL No. 8
Program in J2MEto perform the following tasks:
A) Create a form1 that contain Label &TextBox, Next Button.
B) Create a form2 that contain checkBox, radioButton ,TextArea& Next, Back Button.
C) Create a form3 that contains Display of all above forms.

Code:
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.io.*;
public class Commander extends MIDlet implements CommandListener
{
private CanvasDemo cd;
public Commander()
{
}
Display display = null;
Form f1 = null;
Form f2 = null;
Form f3 = null;
private ChoiceGroup gender;
private int currentIndex;
private int genderIndex;
private ChoiceGroup hobies;
private int hobiesIndex;
private TextField tbName, tbInstitute, tbPhone, tbCel, tbCity, tbArea;
public Ticker ticName;
Command firstFormCommand = new Command("1st Form", "Go to First Form",
Command.SCREEN, 0);
Command secondFormCommand = new Command("2nd Form", "Go to Second Form",
Command.SCREEN, 0);
Command thirdFormCommand = new Command("3rd Form", "Go to Third Form",
Command.SCREEN, 0);
Command exitCommand = new Command("Exit", Command.EXIT, 1);
Command backCommand1 = new Command("Back1", Command.BACK, 1);
Command backCommand2 = new Command("Back2", Command.BACK, 1);
public void startApp()
{
cd=new CanvasDemo(this);
display = Display.getDisplay(this);

f1=new Form("Form 1");


f1.addCommand(secondFormCommand);
f1.addCommand(exitCommand);
f1.setCommandListener(this);
tbName=new TextField("Enter Your Name : ","",20,TextField.ANY);
tbInstitute=new TextField("Name of Institute : ","",20,TextField.ANY);
tbPhone=new TextField("Phone No. : ","",20,TextField.ANY);
tbCel=new TextField("Mobile No. : ","",20,TextField.ANY);
tbCity=new TextField("City : ","",20,TextField.ANY);
ticName=new Ticker("MilindThorat");
f1.append(tbName);
f1.append(tbInstitute);
f1.append(tbPhone);
f1.append(tbCel);
f1.append(tbCity);
f1.setTicker(ticName);
f2=new Form("Form 2");
f2.addCommand(thirdFormCommand);
f2.addCommand(backCommand1);
f2.setCommandListener(this);
hobies=new ChoiceGroup("Select Your Hobies",Choice.MULTIPLE);
hobies.append("Cricket", null);
hobies.append("FootBall", null);
hobies.append("Travel", null);
hobies.append("ReadingBook", null);
hobiesIndex=f2.append(hobies);
gender = new ChoiceGroup("Enter Gender", Choice.EXCLUSIVE);
gender.append("Female", null);
currentIndex = gender.append("Male ", null);
gender.setSelectedIndex(currentIndex, true);
genderIndex = f2.append(gender);
tbArea=new TextField("Educational Interest:","", 100,TextField.ANY);
f2.append(tbArea);
f3=new Form("Form 3");
f3.addCommand(backCommand2);
f3.addCommand(exitCommand);
f3.setCommandListener(this);
display.setCurrent(f1);
}

public void pauseApp() {}


public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d)
{
String label = c.getLabel();
if(label.equals("Exit"))
{
notifyDestroyed();
}
else if(label.equals("1st Form"))
{
Display.getDisplay(this).setCurrent(f1);
}
else if(label.equals("Back1"))
{
Display.getDisplay(this).setCurrent(f1);
}
else if(label.equals("2nd Form"))
{
Display.getDisplay(this).setCurrent(f2);
}
else if(label.equals("Back2"))
{
Display.getDisplay(this).setCurrent(f2);
}
else if(label.equals("3rd Form"))
{
Display.getDisplay(this).setCurrent(f3);
StringItem msg1=new StringItem(null,"\nName: "+ tbName.getString());
StringItem msg2=new StringItem(null,"\nInstitute: "+
tbInstitute.getString());
StringItem msg3=new StringItem(null,"\nPhone No: "+
tbPhone.getString());
StringItem msg4=new StringItem(null,"\nMobile No: "+
tbCel.getString());
StringItem msg5=new StringItem(null,"\nCity: "+ tbCity.getString());
f3.append("Display Result:");
f3.append(msg1);
f3.append(msg2);
f3.append(msg3);
f3.append(msg4);

f3.append(msg5);
boolean picks[] = new boolean[hobies.size()];
StringItemmessage[] = new StringItem[hobies.size()];
hobies.getSelectedFlags(picks);
StringItem msg6= new StringItem(null,"\n Hobies:");
f3.append(msg6);
for (int x = 0; x <picks.length; x++)
{
if (picks[x])
{
message[x] = new StringItem(""," "+hobies.getString(x));
f3.append(message[x]);
}
}
f3.delete(hobiesIndex);
currentIndex = gender.getSelectedIndex();
StringItem message1 = new StringItem("Gender:
",gender.getString(currentIndex));
f3.append(message1);
f3.delete(genderIndex);
StringItem msg7=new StringItem(null,"\nAddress: "+ tbArea.getString());
f3.append(msg7);
}
}
}
classCanvasDemo extends Canvas
{
public Commander parent;
publicintwidth,height;
publicCanvasDemo(Commander parent)
{
this.parent=parent;
width=getWidth();
height=getHeight();
Display.getDisplay(parent).setCurrent(this);
}
public void paint(Graphics g)
{
g.setColor(0,255,0);
g.fillRect(0,0,width,height);
}
}
Output:

PRACTICAL No. 9

Write a program in J2ME to perform the simple calculator operations such as


a. Addition
b. Subtraction
c. Multiplication
d. Division
Code :
importjavax.microedition.midlet.*;
importjavax.microedition.lcdui.*;
public class Calc extends MIDlet implements CommandListener
{
Display disp;
TextField tf1,tf2,tf3;
Form form;
Command add,sub,mul,div,mod,exit;
public Calc()
{
disp=Display.getDisplay(this);
form=new Form("Operation on two numbers");
tf1=new TextField("Firstno.","0",30,TextField.ANY);
tf2=new TextField("Secondno.","0",30,TextField.ANY);
tf3=new TextField("Result","0",30,TextField.ANY);
form.append(tf1);
form.append(tf2);
form.append(tf3);
add=new Command("add",Command.SCREEN,1);
sub=new Command("sub",Command.SCREEN,1);
mul=new Command("mul",Command.SCREEN,1);
div=new Command("div",Command.SCREEN,1);
mod=new Command("mod",Command.SCREEN,1);
exit=new Command("exit",Command.EXIT,1);
form.addCommand(add);
form.addCommand(sub);
form.addCommand(mul);
form.addCommand(div);
form.addCommand(mod);
form.addCommand(exit);

form.setCommandListener(this);
}
public void startApp()
{
disp.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command c,Displayable d)
{
if(c==add)
{
int a=Integer.parseInt(tf1.getString());
int b=Integer.parseInt(tf2.getString());
int c1=a+b;
tf3.setString(String.valueOf(c1));
}
if(c==sub)
{
int a=Integer.parseInt(tf1.getString());
int b=Integer.parseInt(tf2.getString());
int c1=a-b;
tf3.setString(String.valueOf(c1));
}
if(c==mul)
{
int a=Integer.parseInt(tf1.getString());
int b=Integer.parseInt(tf2.getString());
int c1=a*b;
tf3.setString(String.valueOf(c1));
}
if(c==div)
{
int a=Integer.parseInt(tf1.getString());
int b=Integer.parseInt(tf2.getString());
if(b==0)
tf3.setString("Divisor cannot be zero");
else
{
int c1=a/b;
tf3.setString(String.valueOf(c1));
}

}
if(c==mod)
{
int a=Integer.parseInt(tf1.getString());
int b=Integer.parseInt(tf2.getString());
if(b==0)
tf3.setString("Divisor cant be zero");
else
{
int c1=a%b;
tf3.setString(String.valueOf(c1));
}
}
if(c==exit)
{
destroyApp(false);
notifyDestroyed();
}
}
}

Output:

PRACTICAL No. 10
Write a program in J2ME to create a simple Quiz which content 3 to 4 questions and also
display the score.
Code:
importjavax.microedition.midlet.*;
importjavax.microedition.lcdui.*;
importjava.lang.*;
public class QuizDemo extends MIDlet implements CommandListener,
ItemStateListener
{
private Display disp;
private Form form1,form2,form3,form4;
private Command exit,next1,next2,next3,submit;
privateTextBoxmsg;
private Item selection;
privateChoiceGroup radiobuttons,rdb2,rdb3,rdb4;
StringItem ms1,ms2,ms3,ms4;
privateintdefaultIndex;
privateintradioButtonIndex;
int flag=1;
publicQuizDemo()
{
disp=Display.getDisplay(this);
ms1=new StringItem(null,"which following city is capital of India?");
radiobuttons=new ChoiceGroup("Select your
answer",Choice.EXCLUSIVE);
radiobuttons.append("Bangalore",null);
radiobuttons.append("Delhi",null);
radiobuttons.append("Mumbai",null);
radiobuttons.append ("pune",null);
ms2=new StringItem(null,"whichfoilowing city is capital of Japan?");
rdb2=new ChoiceGroup("Select your answer",Choice.EXCLUSIVE);
rdb2.append("yakanua",null);
rdb2.append("Bijieng",null);
rdb2.append("Tokiyo",null);
rdb2.append("ku do su",null);
ms3=new StringItem(null,"whichfoilowing city is capital of UK?");
rdb3=new ChoiceGroup("Select your answer",Choice.EXCLUSIVE);
rdb3.append("Amsterdam",null);
rdb3.append("London",null);
rdb3.append("New york",null);
rdb3.append("Mexico",null);
ms4=new StringItem(null,"Which following city is capital of Egypt?");
rdb4=new ChoiceGroup("Select your answer",Choice.EXCLUSIVE);

rdb4.append("peru",null);
rdb4.append("Rome",null);
rdb4.append("Kairo",null);
rdb4.append("Sydney",null);
form1=new Form("Question 1");
form1.append(ms1);
radioButtonIndex=form1.append(radiobuttons);
form2=new Form("Question 2");
form2.append(ms2);
radioButtonIndex=form2.append(rdb2);
form3=new Form("QueStion 3");
form3.append(ms3);
radioButtonIndex=form3.append(rdb3);
form4=new Form("Question 4");
form4.append(ms4);
radioButtonIndex=form4.append(rdb4);
exit=new Command("Exit",Command.EXIT,1);
submit=new Command("Submit",Command.SCREEN,1);
next1=new Command("Next",Command.SCREEN,1);
next2=new Command("Next",Command.SCREEN,1);
next3=new Command("Next",Command.SCREEN,1);
msg=new TextBox("Message","Congrats",80,0);
form1.addCommand(next1);
form2.addCommand(next2);
form3.addCommand(next3);
form4.addCommand(submit);
form4.addCommand(exit);
form1.setCommandListener(this);
form2.setCommandListener(this);
form3.setCommandListener(this);
form4.setCommandListener(this);
form1.setItemStateListener(this);
form2.setItemStateListener(this);
form3.setItemStateListener(this);
form4.setItemStateListener(this);
}
public void startApp()
{
disp.setCurrent(form1);
}
public void pauseApp()
{

}
public void destroyApp(boolean unconditional)
{
}
public void itemStateChanged(Item item)
{
if(item==radiobuttons)
{
String
ans=(radiobuttons.getString(radiobuttons.getSelectedIndex()));
if(ans.equals("Delhi"))
{
flag++;
}
}
if(item==rdb2)
{
String ans=(rdb2.getString(rdb2.getSelectedIndex()));
if(ans.equals("Tokiyo"))
{
flag++;
}
}
if(item==rdb3)
{
String ans=(rdb3.getString(rdb3.getSelectedIndex()));
if(ans.equals("London"))
{
flag++;
}
}
if(item==rdb4)
{
String ans=(rdb4.getString(rdb4.getSelectedIndex()));
if(ans.equals("kairo"))
{
flag++;
}
}
}
public void commandAction(Command com, Displayable disp1)
{
if(com==next1)

{
disp.setCurrent(form2);
}
if(com==next2)
{
disp.setCurrent(form3);
}
if(com==next3)
{
disp.setCurrent(form4);
}
if(com==exit)
{
destroyApp(false);
notifyDestroyed();
}
if(com==submit)
{
StringItem msg1=new StringItem(null,"You have Correct Answer
"+ flag);
form4.append(msg1);
}
}
}

Output:

PRACTICAL No. 11
Write a program in J2ME to create a currency converter and also display the
result.
Code :
importjavax.microedition.midlet.*;
importjavax.microedition.lcdui.*;
public class currency extends MIDlet implements CommandListener
{
private Display disp;
private Form f;
privateTextFieldtb;
privateTextField tb1;
privateChoiceGroup cg,cg1;
private Command resul;
private Command ans;
public currency()
{
tb=new TextField("","",20,TextField.NUMERIC);
tb1=new TextField("Result","Answer",10,TextField.ANY);
resul=new Command("Result",Command.SCREEN,1);
String[] str1 = { "pound", "Euro", "Dollar","yen" };
String[] str = {"Rupee"};
cg=new ChoiceGroup("",Choice.POPUP,str,null);
cg1 = new ChoiceGroup("",Choice.POPUP,str1,null);
f = new Form("Currency Convertor");
f.append(cg);
f.append(tb);
f.append(cg1);
f.append(tb1);
f.addCommand(resul);
f.setCommandListener(this);
}
public void startApp()
{
disp=Display.getDisplay(this);
disp.setCurrent(f);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)

{
}
public void commandAction(Command c, Displayable s)
{
int n,n1,res=0;
String res1;
n=cg1.getSelectedIndex();
n1=Integer.parseInt(tb.getString());
switch(n)
{
case 0:
res=n1/85;
break;
case 1:
res=n1/75;
break;
case 2:
res=n1/48;
break;
case 3:
res=n1*2;
break;
}
res1=Integer.toString(res);
System.out.println("first="+n1+"\nOperation
Index="+n+"\nResult="+res);
tb1.setString(res1);
}
}

Output :

PRACTICAL No. 12

Write a program in J2ME to generate a calendar.


Code:
importjavax.microedition.lcdui.*;
importjavax.microedition.midlet.MIDlet;
importjava.util.Date;
importjava.util.TimeZone;
public class CalenderMIDlet extends MIDlet{
private Form form;
private Display display;
privateDateFieldcalender;
private static final int DATE = 0;
publicCalenderMIDlet(){
calender = new DateField("Date In:", DateField.DATE, TimeZone.getTimeZone("GMT"));
}
public void startApp(){
display = Display.getDisplay(this);
Form form = new Form("Calender");
form.append(calender);
display.setCurrent(form);
}
public void pauseApp(){}
public void destroyApp(boolean destroy){
notifyDestroyed();
}
}

Output:

PRACTICAL No. 13
Write a program in J2ME to demonstrate simple animation through snake movement.
Code:
importjavax.microedition.midlet.*;
importjavax.microedition.lcdui.*;
public class MySnake extends MIDlet implements CommandListener
{
DrawSnake ds;
Display dis;
publicMySnake()
{
dis =Display.getDisplay(this);
ds=new DrawSnake();
}
public void startApp()
{
dis.setCurrent(ds);
}
public void commandAction(Command c, Displayable d)
{}
public void pauseApp()
{}
public void destroyApp(boolean unconditional)
{}
}
classDrawSnake extends Canvas implements Runnable, CommandListener
{
intx,y,dir;
Thread th;
Command quit;
publicDrawSnake()
{
x=0;
y=0;
dir=0;
quit=new Command("Quit",Command.SCREEN,1);
addCommand(quit);
setCommandListener(this);
th=new Thread(this);
th.start();
}
public void commandAction(Command c,Displayable d)

{
if(c==quit)
{}
}
public void keyPressed(int cd)
{
switch(getGameAction(cd))
{
caseCanvas.UP:
y-=5;
dir=1;
break;
caseCanvas.DOWN:
y+=5;
dir=2;
break;
caseCanvas.LEFT:
x-=5;
dir=3;
break;
caseCanvas.RIGHT:
x+=5;
dir=4;
break;
}
}
public void run()
{
while(true)
{
if(dir==1)
y-=5;
else if(dir==2)
y+=5;
else if(dir==3)
x-=5;
else if(dir==4)
x+=5;
repaint();
try
{
th.sleep(500);
}
catch(Exception ee)
{
}

}
}
public void paint(Graphics g)
{
g.setColor(0x1F2F1F);
g.fillRect(x,y,10,10);
g.drawString("Milind Thorat",25,25,Graphics.TOP | Graphics.LEFT);
}
}

Output:

PRACTICAL No. 14
Write a program in J2ME to create a simple database application with an address book
with the following operations:
a. Insert
b. Delete
c. Update
d. Retrieve

Code:
import java.io.*;
importjava.util.*;
importjavax.microedition.midlet.*;
importjavax.microedition.lcdui.*;
import javax.microedition.io.*;
public class MySQLConn extends MIDlet implements CommandListener
{
private String username;
private String url="http://localhost:8080/jj/getConnection";
private Display display;
private Command exit=new Command("EXIT", Command.EXIT,1);
private Command connect=new Command("Connect", Command.SCREEN,1);
private Form menu;
privateTextField tb1;
privateTextField tb2;
DBConndb;
publicMySQLConn() throws Exception
{
display=Display.getDisplay(this);
}
public void startApp()
{
displayMenu();
}
public void displayMenu()
{
menu=new Form("Connect");
tb1=new TextField("Please input username:","",30,TextField.ANY);
tb2=new TextField("Please input password:","",30,TextField.PASSWORD);
menu.append(tb1);
menu.append(tb2);
menu.addCommand(exit);
menu.addCommand(connect);

menu.setCommandListener(this);
display.setCurrent(menu);
}
public void pauseApp()
{}
public void destroyApp(boolean unconditional)
{}
public void commandAction(Command command,Displayable screen)
{
if(command==exit)
{
destroyApp(false);
notifyDestroyed();
}
else if(command==connect)
{
db=new DBConn(this);
db.start();
db.connectDb(tb1.getString(),tb2.getString());
}
}
public class DBConn implements Runnable
{
MySQLConnmidlet;
private Display display;
String db;
String user;
String pwd;
publicDBConn(MySQLConnmidlet)
{
this.midlet=midlet;
display=Display.getDisplay(midlet);
}
public void start()
{
Thread t=new Thread(this);
t.start();
}
public void run()
{
StringBuffersb=new StringBuffer();
try
{
HttpConnection c=(HttpConnection) Connector.open(url);

c.setRequestProperty("User-Agent","Profile/MIDP-1.0,
Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);
DataOutputStreamos=(DataOutputStream)c.openDataOutputStream();
os.writeUTF(user.trim());
os.writeUTF(pwd.trim());
os.flush();
os.close();
DataInputStream is=(DataInputStream)c.openDataInputStream();
intch;
sb=new StringBuffer();
while((ch=is.read())!=-1)
{
sb.append((char)ch);
}
showAlert(sb.toString());
is.close();
c.close();
}
catch(Exception e)
{
showAlert(e.getMessage());
}
}
public void connectDb(String user,Stringpwd)
{
this.user=user;
this.pwd=pwd;
}
private void showAlert(String err)
{
Alert a=new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
};
}
Servlet Code for JDBC Connection:
import java.io.*;

importjavax.servlet.*;
importjavax.servlet.http.*;
import java.sql.*;
public class getConnection extends HttpServlet
{
Connection conn;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
DataInputStream in=new
DataInputStream((InputStream)request.getInputStream());
String user=in.readUTF();
String pwd=in.readUTF();
System.out.println("received data is==>"+user+pwd);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:milu");
Statement stmt=conn.createStatement();
inti=stmt.executeUpdate("insert into Login
Values('"+user+"','"+pwd+"')");
if(i!=0)
{
out.println("Hi, Milind, Data has Inserted Successfully");
}
else
{
out.println("iData is Not inserted");
}
}
catch(Exception e)
{
e.printStackTrace();
}
out.println("Your Name is: "+user+"\n Your Password is:"+pwd);
in.close();
out.close();
out.flush();
}
public void doget(HttpServletRequestrequest,HttpServletResponse response)
throwsServletException, IOException

{
doPost(request,response);
}
}

Output:

You might also like