Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Mobile Application Development Lab SAMPLE PROGRAM: Printing “Helloworld” program in J2ME Procedure: Step 1: Start->AllPrograms->SunJavaToolKit->WirelessToolKit Step 2: Click New Project->Enter Project Name as FirstMidlet->Enter ClassName as HelloMidlet->Click on Create Project Step 3: A Setting window will open up. Accept the defaults by clicking ok in that window. Step 4: Write following code in Notepad and save it as HelloMidlet.java import javax.microedition.midlet.*; import javax.microedition.lcdui.*; 1 public class HelloMidlet extends MIDlet { public HelloMidlet() { }public void startApp() { Form form = new Form( "First Program" ); form.append( "Hello World" ); Display.getDisplay(this).setCurrent( form ); }public void pauseApp() { }public void destroyApp( boolean unconditional ) {}} Step 5: Place HelloMidlet.java in C:\Users\Administrator\j2mewtk\2.5.2\apps\FirstMidlet\src Step 6:In Wireless Tool Kit window click on Build. If Build is successfully completed, then click on Run. 2 1. Write a J2ME program to show how to change the font size and colour. Code: import javax.microedition.lcdui.*; import javax.microedition.midlet.*; import java.io.*; import java.lang.*; import javax.microedition.io.*; import javax.microedition.rms.*; public class changeFont extends MIDlet { public static final boolean COLOR = false; public static final boolean DEBUG = false; public static final int WHITE = 0xFFFFFF; public static final int BLACK = 0x000000; public static final int RED = 0xFF0000; public static final int GREEN = 0x00FF00; public static final int BLUE = 0x0000FF; public static final int LIGHT_GRAY = 0xAAAAAA; public static final int DARK_GRAY = 0x555555; private Display myDisplay = null; private DecodeCanvas decodeCanvas = null; private boolean painting = false; public changeFont() { myDisplay = Display.getDisplay(this); decodeCanvas = new DecodeCanvas(this); } public void startApp() throws MIDletStateChangeException { myDisplay.setCurrent(decodeCanvas); } public void pauseApp() { } protected void destroyApp(boolean unconditional) throws MIDletStateChangeException { } class DecodeCanvas extends Canvas { private changeFont parent = null; private int width = getWidth(); private int height = getHeight(); public DecodeCanvas(changeFont parent) { this.parent = parent; } public void paint(Graphics g) { g.setColor(WHITE); g.fillRect(0, 0, width, height); Font f1 = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_LARGE); Font f2 = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_MEDIUM); Font f3 = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL); int yPos = 0; if (COLOR) g.setColor(BLUE); else g.setColor(LIGHT_GRAY); g.fillRect(0, yPos, width, f1.getHeight()); if (COLOR) g.setColor(WHITE); else g.setColor(GREEN); g.setFont(f1); g.drawString("BIG FONT", 0, yPos, Graphics.LEFT | Graphics.TOP); 3 // yPos = yPos + f1.getHeight() + 10; g.setColor(RED); g.setFont(f2); g.drawLine(0, f1.getHeight() + yPos - 1, width, f1.getHeight() + yPos - 1); g.drawString("MEDIUM FONT", 0, yPos, Graphics.LEFT | Graphics.TOP); g.setColor(BLUE); //g.drawLine(0, f2.getHeight() + yPos - 1, width, f2.getHeight() + yPos - 1); yPos = yPos + f1.getHeight() + 10; g.setFont(f3); g.drawString("SMALL FONT", 0, yPos, Graphics.LEFT | Graphics.TOP); yPos = yPos + f1.getHeight() + 10; g.setColor(BLACK); g.drawLine(0, f3.getHeight() + yPos - 1, width, f3.getHeight() + yPos - 1); painting = false; }} } 4 2. Write a J2ME program which creates the following kind of menu. * cut * copy * past * delete * select all * unselect all 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 command; 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); command=new Command("Select List Item",Command.OK,1); form=new Form(""); form.append(ch); form.addCommand(command); form.setCommandListener(this); st=new StringItem("",""); } public void startApp() { display.setCurrent(form); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command command,Displayable disaplayable) { if(command==command) { st.setText(""); st.setText("your selected option is "+ch.getString(ch.getSelectedIndex())); form.append(st); } }} 5 3. Create a J2ME menu which has the following options (Event Handling): cut - can be on/off copy - can be on/off paste - can be on/off delete - can be on/off select all - put all 4 options on unselect all - put all Code: import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class MenuEvents extends MIDlet implements CommandListener,ItemStateListener { public ChoiceGroup ch,ch1; public Form form,form1; public Display display; public Command View, Exit, Back; public StringItem options; public Item item; public MenuEvents() { display=Display.getDisplay(this); form=new Form(""); form1=new Form("Selected Options are"); 6 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); 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); } 7 else if(command==Exit) { destroyApp(true); notifyDestroyed(); } } else 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++; }}}} 8 4. Create a MIDP application, which draws a bar graph to the display. Data values can be given at int[] array. You can enter four data (integer) values to the input text field. 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); } 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()); 9 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()); 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 , y); x+=30; i++;}} } 10 5. Create an MIDP application which examine, that a phone number, which a user has entered is in the given format (Input checking): * Area code should be one of the following: 040, 041, 050, 0400, 044 * There should 6-8 numbers in telephone number (+ area code) 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("Enter Phone:","",30,TextField.ANY); form1.append(textfield1); form1.addCommand(okCommand); form1.addCommand(exitCommand); form1.setCommandListener(this); } public void startApp() { 11 display.setCurrent(form1); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command cmd,Displayable displayable) { if(cmd==exitCommand) 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); }}} 12 6. Write a sample program to show how to make a SOCKET Connection from J2ME phone. This J2ME sample program shows 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. Show how to make a SOCKET connection from the phone to port 80. Description: Sockets are different than datagrams because they use a connection-based paradigm to transmit data. This means that both a sender and a receiver must be running and establish a communication channel for data to be exchanged. To use a real-world analogy, a socket connection is like calling a friend on the telephone. If the friend does not answer, a conversation cannot take place. Datagrams on the other hand are more like sending a letter to a friend, where a note is placed into an envelope, addressed, and mailed. 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; 13 // 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(); 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 { 14 // free up I/O streams and close the socket connection try { if (dataInputStream != null) dataInputStream.close(); } catch (Exception ignored) {} try { 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) { } } 15 7. This J2ME sample program shows how to display a simple LOGIN SCREEN on the J2ME phone and how to authenticate to a HTTP server. Many J2ME applications for security reasons require the authentication of the user. This free J2ME sample program shows how a J2ME application can do authentication to the backend server. /* * A free J2ME sample program to demonstrate * a SIMPLE LOGIN SCREEN TO LOGIN TO A HTTP SERVER * FROM A J2ME phone * * @author William Alexander * free for use as long as this comment is included in * in the program as it is * More Free Java programs available for download * at http://www.java-samples.com * */ 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); } 16 public void startApp() throws MIDletStateChangeException { } public void pauseApp() { } protected void destroyApp(boolean unconditional) throws MIDletStateChangeException { } public void commandAction(Command c, Displayable d) { 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/CLDC1.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); 17 //System.out.println((char)ch); } //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); } } 8. Web Application using J2ME 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. Develop a simple Java ME project to retrieve student marks when regd.no is given Note: Use Apache Tomcat Server as Web Server and Mysql as Database Server. Procedure: Step1: Create a database table with the following commands. (Assume that 'mysql' database is installed in 'c:\mysql' folder) c:\>cd mysql c:\mysql>cd bin c:\mysql\bin>mysql mysql> create database stud; Query OK, 1 row affected (0.04 sec) mysql> use stud; Database changed mysql> create table student(sno varchar(10),name varchar(20),moad integer(2),ws integer(2),spm integer(2),st integer(2),ds integer(2),mefa integer(2)); Query OK, 0 rows affected (0.01 sec) mysql> insert into student values('10731a1227','venkat',66,77,88,66,77,88); Query OK, 1 row affected (0.00 sec) Step 2: Create a 'jsp' file with the following code <%@ page import ="java.sql.*" %> <%@ page import ="javax.sql.*" %> <%@ page import ="java.io.*" %> <% DataInputStream in = new DataInputStream((InputStream)request.getInputStream()); String rollno=in.readUTF(); Class.forName("com.mysql.jdbc.Driver"); 18 java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/stud","dayakar",""); Statement st= con.createStatement(); ResultSet rs=st.executeQuery("select * from student where sno='"+rollno+"'"); if(rs.next()) { String message; if(rs.getString(1).equals(rollno)) { message = "Student Name:"+rs.getString(2)+"\nMarks in MoAD:"+rs.getInt(3)+"\nMarks in WS:"+rs.getInt(4)+"\nMarks in SPM:"+rs.getInt(5)+"\nMarks in ST:"+rs.getInt(6)+"\nMarks in DS:"+ rs.getInt(7)+"\nMarks in MEFA:"+rs.getInt(8); } else { message = "Login Failure"; } out.println(message); } %> Install Tomcat Server 6.0 and deploy this 'jsp' program in the following directory structure webapps | | ----test4 | | -----WEB-INF | |--lib--mysql-connector-java-3.0.8-stable-bin.jar | ----login.jsp Note: You can download 'mysql-connnector-java-3.0.8-stable-bin.jar' from the link 'http://mirrors.ibiblio.org/maven2/mysql/mysql-connector-java/3.0.8/' Adding this jar file is mandatory to make sure that this program is running Step 3: Create a Java ME program with the following code and deploy in either wireless toolkit or netbeans IDE import javax.microedition.lcdui.*; import javax.microedition.midlet.*; import javax.microedition.io.*; import java.io.*; public class StudentMidlet extends MIDlet implements CommandListener { Display display; Form form; TextField tf; String str; String url= "http://localhost:7000/test4/login.jsp"; Command back= new Command("Back", Command.BACK, 0); Command submit= new Command("Submit", Command.OK, 2); Command exit= new Command("Exit", Command.STOP, 3); private StudentMidlet.Test test; public StudentMidlet() {} 19 public void startApp() throws MIDletStateChangeException { display = Display.getDisplay(this); form = new Form("Student Information Retrieval"); tf = new TextField("Enter Student No:","",30,TextField.ANY ); form.append(tf); form.addCommand(submit); form.addCommand(exit); form.setCommandListener(this); display.setCurrent(form); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable d) { if (c == exit) { destroyApp(true); notifyDestroyed(); } else if (c == back) { display.setCurrent(form); } else if (c == submit) { str = tf.getString(); test = new StudentMidlet.Test(this); test.start(); test.setString(str); } } class Test implements Runnable { StudentMidlet midlet; private Display display; String text; public Test(StudentMidlet 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(text.trim()); os.flush(); os.close(); // Get the response from the servlet page. DataInputStream is =(DataInputStream)c.openDataInputStream(); 20 //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 text and pass to jsp */ public void setString(String text) { this.text = text; } /* Display Output or Error On screen*/ private void showAlert(String str) { Alert a = new Alert(""); a.setString(str); a.setTimeout(Alert.FOREVER); display.setCurrent(a); } }; } Step 4: The output is displayed on the mobile emulator as shown below on Student Information will be displayed as shown in the following mobile emulator Town/City Movie Enquiry movie.java import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; import java.io.*; public class movie extends MIDlet implements CommandListener { public Form form1; public Command okCommand; public Display display; public HttpConnection ht=null; public InputStream ist=null; public StringItem st; public TextField t1; public Alert alert; public Form form2; public movie() { display=Display.getDisplay(this); st=new StringItem(""," eg:-Mahesh"); alert=new Alert("","Enter correct moviename/movie not available in City",null,AlertType.INFO); t1=new TextField("ENTER Movie Name:-","",12,TextField.ANY); form1=new Form("WELCOME TO RESULTS"); 21 form2=new Form("Theatre DEtails"); okCommand=new Command("GET",Command.OK,1); Command back=new Command("BACK",Command.OK,0); form1.addCommand(okCommand); form2.addCommand(back); form1.setCommandListener(this); form2.setCommandListener(this); form1.append(t1); form1.append(st); } public void startApp() { display.setCurrent(form1); } public void pauseApp() {} public void destroyApp(boolean unconditional) { notifyDestroyed(); } public void commandAction(Command cmd,Displayable d) { if(cmd==okCommand) { Thread t=new Thread() { public void run() { connect(); } }; t.start(); } } private void connect() { try { String url="http://localhost:8081/week9/index.jsp?t1="+t1.getString().trim(); ht=(HttpConnection)Connector.open(url); ist=ht.openInputStream(); byte[] b=new byte[900]; ist.read(b); String s=new String(b); s=s.trim(); if(s.equals("no")) { alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } else { form2.append(s); display.setCurrent(form2); 22 } } catch(Exception ex) { form1.append(ex.toString()); } } } index.jsp <%@page import="java.sql.*,java.io.*"%> <% String id=request.getParameter("t1"); String sql="select * from movie"; String DP="",MC="",DS="",CNS="",s=""; int count=0; try{ Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("Driver Registered"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","tiger ") ; System.out.println("connection established"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery(sql); while(rs.next()) { s=rs.getString(1); if(id.equals(s)) { DP=rs.getString(2); CNS=rs.getString(3); DS=rs.getString(4); count++; } } if(count==1) { out.println("Movie Name::"+id); out.println("\nTheatre:- "+DP); out.println("\nNumber:- "+CNS); out.println("Show timing:- "+DS); } else { out.println("no"); } } catch(Exception ex) { out.println(ex.toString()); out.close(); } %> 23 9. Write an Android application program that displays Hello World using Terminal. Code: Set the following paths: Right click on Computer. Click on properties and then Click on Advanced system setting Click on Environment Variables . Goto System variables. Select the path and set the paths as follows. 1. C:\Program Files\Java\jdk1.7.0_45\bin; 2. C:\Program Files\Java\jdk1.7.0_03\lib;(copy tools file and place in the following path.( C:\Program Files\Java\jre7\lib) 3. C:\Program Files\Java\jre7\lib; 4. C:\apache-ant-1.9.2\bin; 5. C:\adt-bundle-windows-x86-20130522\sdk\tools; 6. C:\adt-bundle-windows-x86-20130522\sdk\platform-tools; 7. Click on OK Step 1: Open command prompt Step 2: goto D:\adt-bundle-windows-x86-20130522\sdk\tools Step 3: Create a new AVD by the following command android create avd –n <avdname> -t <android API level> android API level value is android-17 Step 4: Run the avd by the following command emulator –avd <avdname> 24 25 \ 10. Write an Android application program that displays Hello World using Eclipse. Code: package com.example.helloworld; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); 26 } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } Activity_main.xml : <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </RelativeLayout> Output: 27 11. Write an Android application program that accepts a name from the user and displays the hello name to the user in response as output using Eclipse. Code: MainActivity.java package com.example.app1; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText et=(EditText)findViewById(R.id.editText1); Button b1=(Button)findViewById(R.id.button1); 28 b1.setOnClickListener(new OnClickListener() { String et1; @Override public void onClick(View arg0) { // TODO Auto-generated method stub et1="Hello "+et.getText().toString().trim(); Toast.makeText(getApplicationContext(),et1, Toast.LENGTH_LONG).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } Activitymain.xml <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="31dp" android:layout_marginTop="74dp" android:text="Enter Name" android:textAppearance="?android:attr/textAppearanceLarge"/> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:ems="10"> <requestFocus/> </EditText> <Button android:id="@+id/button1" 29 android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="CLICK"/> </RelativeLayout> 12. Write an Android application program that demonstrates the following: (i) LinearLayout (ii) RelativeLayout (iii) TableLayout (iv) GridView layout Code: (i) Linear Layout <?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingLeft="16dp" android:paddingRight="16dp" android:orientation="vertical"> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="To"/> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Subject"/> <EditText 30 android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" android:gravity="top" android:hint="Message"/> <Button android:layout_width="100dp" android:layout_height="wrap_content" android:layout_gravity="right" android:text="Send"/> </LinearLayout> (ii) Relative Layout <?xmlversion="1.0"encoding="utf-8"?> <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingLeft="16dp" android:paddingRight="16dp"> <RelativeLayout android:id="@+id/relativeLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="48dp" android:layout_marginTop="146dp"> </RelativeLayout> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="49dp" android:text="Select Deaprtment" android:textAppearance="?android:attr/textAppearanceLarge"/> 31 <CheckBox android:id="@+id/checkBox1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/relativeLayout1" android:layout_marginBottom="15dp" android:layout_toLeftOf="@+id/textView1" android:text="CSE"/> <CheckBox android:id="@+id/checkBox2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/checkBox1" android:layout_alignParentRight="true" android:layout_marginRight="44dp" android:text="IT"/> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/checkBox1" android:layout_centerHorizontal="true" android:text="CLICK"/> </RelativeLayout> (iii) Table Layout <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:shrinkColumns="*"android:stretchColumns="*"android:background="#ffffff"> <!-- Row 1 with single column --> <TableRow android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center_horizontal"> 32 <TextView android:layout_width="match_parent"android:layout_height="wrap_content" android:textSize="18dp"android:text="Row 1"android:layout_span="3" android:padding="18dip"android:background="#b0b0b0" android:textColor="#000"/> </TableRow> <!-- Row 2 with 3 columns --> <TableRow android:id="@+id/tableRow1" android:layout_height="wrap_content" android:layout_width="match_parent"> <TextView android:id="@+id/TextView04"android:text="Row 2 column 1" android:layout_weight="1"android:background="#dcdcdc" android:textColor="#000000" android:padding="20dip"android:gravity="center"/> <TextView android:id="@+id/TextView04"android:text="Row 2 column 2" android:layout_weight="1"android:background="#d3d3d3" android:textColor="#000000" android:padding="20dip"android:gravity="center"/> <TextView android:id="@+id/TextView04"android:text="Row 2 column 3" android:layout_weight="1"android:background="#cac9c9" android:textColor="#000000" android:padding="20dip"android:gravity="center"/> </TableRow> </TableLayout> (iv) GridView Layout 33 Gridview is mainly useful when we want show data in grid layout like displaying images or icons. This layout can be used to build applications like image viewer, audio or video players in order to show elements in grid manner. Step 1: Create a new project by going to File ⇒ New AndroidProject⇒ App2 Step 2:Prepare images which should be displayed in grid layout and place them in res ⇒ drawable-hdpi folder (image names should be pic_1, pic_2, …). Step 3:Create a new XML layout under layout and name it as grid_layout layout ⇒ New ⇒ Android XML File grid_layout.xml <?xmlversion="1.0"encoding="utf-8"?> <GridViewxmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/grid_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:numColumns="auto_fit" android:columnWidth="90dp" android:horizontalSpacing="10dp" android:verticalSpacing="10dp" android:gravity="center" android:stretchMode="columnWidth"> </GridView> Step 4: Create a new Class by right clicking on (Right Click) src ⇒ package folder ⇒ New ⇒ Class and name as ImageAdapter ImageAdapter.java package com.example.androidhive; import com.example.app2.R; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; 34 public class ImageAdapter extends BaseAdapter { private Context mContext; // Keep all Images in array public Integer[] mThumbIds = { R.drawable.pic_1, R.drawable.pic_2, R.drawable.pic_3, R.drawable.pic_4, R.drawable.pic_5, R.drawable.pic_6, R.drawable.pic_7, R.drawable.pic_8 }; // Constructor public ImageAdapter(Context c){ mContext = c; } @Override public int getCount() { return mThumbIds.length; } @Override public Object getItem(int position) { return mThumbIds[position]; } @Override public long getItemId(int position) { 35 return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(mContext); imageView.setImageResource(mThumbIds[position]); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setLayoutParams(new GridView.LayoutParams(70, 70)); return imageView; } } MainActivity.java package com.example.app2; import com.example.androidhive.ImageAdapter; import android.app.Activity; importandroid.content.Intent; import android.os.Bundle; importandroid.view.View; importandroid.widget.AdapterView; importandroid.widget.AdapterView.OnItemClickListener; import android.widget.GridView; publicclass MainActivity extends Activity { @Override publicvoid onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.grid_layout); GridView gridView = (GridView) findViewById(R.id.grid_view); // Instance of ImageAdapter Class gridView.setAdapter(new ImageAdapter(this)); } } 36 13. Write an Android application program that converts the temperature in Celsius to Fahrenheit. Code: MainActivity.java package com.example.app3; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bt=(Button)findViewById(R.id.button1); final EditText et=(EditText)findViewById(R.id.editText1); bt.setOnClickListener(new OnClickListener() { @Override 37 public void onClick(View arg0) { // TODO Auto-generated method stub String st1=et.getText().toString().trim(); float x=Float.parseFloat(st1); float y=(x*9/5)+32; String st2="Result="+y; Toast.makeText(getApplicationContext(), Toast.LENGTH_LONG).show(); } }); } st2, @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } ActivityMain.xml <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="24dp" android:layout_marginTop="36dp" android:text="Enter Temp in Celsius" android:textAppearance="?android:attr/textAppearanceLarge"/> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:layout_marginTop="35dp" android:ems="10"> <requestFocus/> </EditText> <Button 38 android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="Convert To Forenheit"/> </RelativeLayout> 39 14. Write an Android application program that demonstrates intent in mobile application development. Code: activity_main.xml <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="67dp" android:text="LOGIN"/> </RelativeLayout> login.xml <?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Login ID" android:layout_gravity="center_horizontal" android:textAppearance="?android:attr/textAppearanceLarge"/> <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPersonName"> <requestFocus/> </EditText> 40 <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Password" android:layout_gravity="center_horizontal" android:textAppearance="?android:attr/textAppearanceLarge"/> <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPassword"/> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Login"/> </LinearLayout> mainactivity.java package com.example.qwe1; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bt1=(Button)findViewById(R.id.button1); Button bt2=(Button)findViewById(R.id.button2); bt1.setOnClickListener(new OnClickListener() { 41 @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent = new Intent(MainActivity.this, login.class); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } login.java package com.example.qwe1; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class login extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); } } AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> 42 <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.prj1" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.prj1.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.prj1.login" android:label="@string/app_name" > </activity> </application> </manifest> 43 s 44