Vous êtes sur la page 1sur 126

INDEX

S.No
1.

2.

3.

4.

5.

Date

Experiment Name
1. Write a J2ME program to show
how to change the font size and
color.
2. Write a J2ME program which
creates the following kind of
menu.
* cut
* copy
* paste
* delete
* select all
* unselect all
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
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.
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)

Page.
No

Marks

Remarks

6.

7.

8.

9.
10.

6. Write 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. Show how to make a
SOCKET connection from the
phone to port 80.
7. Login to HTTP Server from a
J2ME Program. 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. Note:
Use
Apache Tomcat Server as Web
Server and MySQL as Database
Server.
8. 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
9. Write an Android application
program that displays
Hello
World using Terminal.
10. Write an Android application
program that displays
Hello
World using Eclipse.

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.
12. Write an Android application
program that demonstrates the
following:
(i) LinearLayout
(ii) RelativeLayout
(iii) TableLayout
(iv) GridView layout
13. Write an Android application
program that converts
the
temperature in Celsius
to
Fahrenheit.
14.Write
an Android application
program that demonstrates intent
in
mobile
application
development

11.

12.

13.

14.

What is J2ME?
J2ME is the short form for Java 2 Micro Edition. J2ME is meant for small devices such as
mobile phones, TV set top boxes, Vehicle telemetric, pagers, PDAs etc.
There are many differences between J2ME and other Editions of Java. The reason being the
target devices of J2ME are very much different from the Computers.
Some of the main differences between computers and the J2ME devices are:

Limited processing power


Limited system memory
Limited storage capacity

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 3

Small display
Less Battery power
Limited connectivity to internet

Types of configurations in J2ME:A configuration defines the minimum Java technology that an application developer can
expect on a broad range of implementing devices.
J2ME currently defines two configurations:
1. Connected Limited Device Configuration (CLDC)
2. Connected Device Configuration (CDC)
1) Connected Limited Device Configuration (CLDC): Specifies the Java environment for mobile phone, pager and wireless devices
CLDC devices are usually wireless
160 - 512k of memory available for Java
Typically has limited power or battery operated
Network connectivity, often wireless, intermittent, low-bandwidth (9600bps or less)
2) Connected Device Configuration (CDC): Describes the Java environment for digital television set-top boxes, high end wireless
devices and automotive telemetric systems.
Device is powered by a 32-bit processor
2MB or more of total memory available for Java
Network connectivity, often wireless, intermittent, low-bandwidth (9600bps or less)

Types of Profiles in J2ME:A specification layer above the configuration which describes the Java configuration for a
specific vertical market or device type.
Both J2ME configurations have one or more associated profiles, some of which may
themselves rely on other profiles.
Mobile Information Device Profile (MIDP)
PDA Profile (PDAP)
Foundation Profile
Personal Basis and Personal Profiles
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 4

RMI Profile
Game Profile
Application Development:MIDlets vs Applets:

MIDlets are applets for mobile phones.


Just like applets, they run in a protected sandbox - the KVM - but unlike applets, they
are extremely limited.
MIDP 1.0 is currently found on most Java-capable phones and is fairly restrictive.
Example:-The KVM doesn't allow you to process floating point numbers yet and
MIDlets written for MIDP 1.0 can't access anything outside of the sandbox without
proprietary APIs from phone manufacturers.
So, put your dreams of developing the ultimate MIDlet with hooks into every part of
your phone OS on the backburner for a while.
If you want to find out exactly how limited MIDP 1.0 is, you should probably read the
spec here.
Once you've done that you might want to check out MIDP 2.0 and see what Sun has
fixed with that spec.
For the time being we're going to write our first MIDlet - a full-featured "Hello MIDlet"
application.

Simple HelloMIDlet
Go to StartPrograms Sun Java (TM) Wireless Toolkit 2.5.2 for CLDC
Wireless Toolkit 2.5.2.
Click on the New Project button and name your project HelloProject and your
MIDlet HelloMidlet.
Once you press Create Project, Wireless tool kit will create a bunch of directories
for your project in the apps subdirectory. We're going to ignore most of them for
the moment and focus on a few important ones
C:\j2mewtk\apps\HelloProject - the main directory for your project
C:\j2mewtk\apps\HelloProject\bin - where Wireless tool kit stores .jar, .jar
and manifest.mf files
C:\j2mewtk\apps\HelloProject\classes - where the class files are stored
C:\j2mewtk\apps\HelloProject\src - where the source .java files are stored
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 5

Creating the Helloworld project:Step:-1 Click on Wireless Toolkit 2.5.2 under the group: All ProgramsSun Java(TM) Wireless
Toolkit 2.5.2 Wireless Toolkit 2.5.2
Step:-2 Click on 'New Project...' button.

Step:-3 Enter project name as 'Helloworld'. Enter MIDlet name as 'Helloworld'. Note that the
Midlet name is the same as the name of the class in the source code, which extends the
MIDlet class, otherwise your application wont run.

Step:-4 Another window pops up where you have to select a target platform. Select 'MIDP 1.0'
from the drop down list.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 6

Step:-5 After you click OK, the project is created and the Wireless Toolkit tells you the name of
the folder where you can create your source code files. The path of the source code
folder is displayed in the debug output window as shown below.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 7

Creating a New Project


Creating and Compiling the Helloworld source files:The Wireless Toolkit does not come with an IDE by default so feel free to use an IDE of your
choice or a text editor like Notepad.
Step:-1 Create a new text file called Helloworld.java in the source folder of the project. The
exact path of this folder is displayed in the Wireless Toolkit window as shown above.
Step:-2 Paste contents of listing 9.6 (Helloworld.java) from
Step:-3 Then click on the Build button in the Wireless Toolkit window. If the compilation is
OK, it will say Build Complete in the window's debug output window, otherwise it will
show you the errors. Note: In your source code, you can use the System.out.println()
statement to output debug information to this window.
Step:-4 After compiling your project successfully, click on the Run button in the Wireless
Toolkit window.
Step:-5 A graphical window depicting a phone handset will appear with the name of your
application highlighted on its screen as shown below.
Step:-6 To start the application, click on the right soft-key (marked with a dot) below the
Launch command.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 8

1. Write a j2me program to show how to change the font size and colour
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 9

Class name: changeFont.java


Program: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 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;
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 10

}
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(BLACK);
g.setFont(f1);
g.drawString("BIG FONT", 0, yPos, Graphics.LEFT | Graphics.TOP);
yPos = yPos + f1.getHeight() + 10;
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(BLACK);
//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.drawLine(0, f3.getHeight() + yPos - 1, width, f3.getHeight() + yPos - 1);
painting = false;
}
}
}

OUTPUT:-

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 11

2. Create a program which creates to following kind of menu.


* cut
* copy
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 12

* paste
* delete
* select all
* unselect all
Class name: menucreation
Program: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()
{
}

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 13

public void destroyApp(boolean unconditional)


{
}
public void commandAction(Command command,Displayable displayable)
{
if(command==command)
{
st.setText("");
st.setText("your selected option is "+ch.getString(ch.getSelectedIndex()));
form.append(st);
}
}
}
OUTPUT:-

3. Create A Program Which Creates A Select Menu For Event Handling


* cut - can be on/off
* copy - can be on/off
* paste - can be on/off
* delete - can be on/off
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 14

* select all - put all 4 options on


* unselect all - put all 4 options off
Class name: menuevents
Program: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);
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 15

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++)
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 16

{
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 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<0)
{
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 17

if(ch1.getSelectedIndex()==0)
ch.setSelectedIndex(i, true);
else
ch.setSelectedIndex(i, false);
i++;
}
}
}
}
OUTPUT:-

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 18

4. Create a MIDP application,which draws a bargraph to display.Data values can be given


at int[ ]array?
Class name: bargraph
Program:import javax.microedition.midlet.*;
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 19

import javax.microedition.lcdui.*;
public class bargraph 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 bargraph()
{
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)
{
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 20

}
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());
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 21

g.setColor(255, 125, 100);


y1=data[0];
h=200;
for(int i=0;i<5;i++)
{
y=100-data[i];
h=100-y;
g.fillRect(x,y,25,h);
x+=30;
i++;
}
}
}
OUTPUT:-

5. Create a MIDP application which Examine, that a phone number, which a user entered
in given format.
Class name: inputchecking
Program:import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 22

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)
notifyDestroyed();
else if(cmd==okCommand)
{
String s=textfield1.getString();
s=s.replace(' ', '.');

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 23

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");
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 24

}
form1.append(st);
}
}
}
OUTPUT:-

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 25

6. Write 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.
Class name: socket.java
Program: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;
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 26

//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);
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 27

}
finally
{
//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()
{
}
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 28

public void destroyApp(boolean unconditional)


{
}
}

OUTPUT:-

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 29

7. Login to HTTP Server from a J2ME Program. 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. Note: Use Apache Tomcat Server as Web Server
and MySQL as Database Server.
Class name: Demo.java
Program:import java.io.*;
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
public class Demo extends MIDlet implements CommandListener
{
private String username;
private String url = "http://localhost:8082/mobileDemo/indexDB.jsp";
private Display display;
private Command exit = new Command("EXIT", Command.EXIT, 1);
private Command login = new Command("Login", Command.SCREEN, 1);
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 30

private Form menu;


private TextField tb1;
private TextField tb2;
DBConn db;
public Demo() throws Exception
{
display = Display.getDisplay(this);
}
public void startApp()
{
displayMenu();
}
public void displayMenu() {
menu = new Form("Login Form");
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(login);
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 == login)
{
db = new DBConn(this);
db.start();
db.connectDb(tb1.getString(),tb2.getString());
}
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 31

}
public class DBConn implements Runnable
{
Demo midlet;
private Display display;
String user;
String pwd;
public DBConn(Demo 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(user.trim());
os.writeUTF(pwd.trim());
os.flush();
os.close();
// Get the response from the page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1)
{
sb.append((char)ch);
}
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 32

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.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);
}
};
}
indexDB.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.ResultSet"%>
<%@ page import="java.sql.DriverManager"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.Statement"%>
<%@page import="javax.swing.JOptionPane" %>
<%
boolean found = false;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:hari","system","manager");
Statement statement = con.createStatement();
String name = request.getParameter("username");
String pwd = request.getParameter("password");
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 33

String sqlQuery = "select * from emp where username='"


+ name + "'AND password='" + pwd + "'";
ResultSet result = statement.executeQuery(sqlQuery);
while (result.next())
{%>
<% out.println(result.getString(1));
out.println(result.getString(2));
%>
<% } %>
<%con.close ();
%>

Output:

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 34

8(a). 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;z
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)
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 35

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");
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
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 36

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()
{
}
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);
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 37

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();
//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());
}
}
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 38

/* 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.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 39

8(b). Develop a simple Java ME project on City Movie Enquiry.


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 movie;
Query OK, 1 row affected (0.07 sec)
mysql> use movie;
Database changed
mysql> create table movie(theatre varchar(20),movie varchar(30));
Query OK, 0 rows affected (0.09 sec)
mysql> insert into movie values('narthaki','attarintikidaredi');
Query OK, 1 row affected (0.00 sec)
Step 2: Create a 'jsp' file with the following code
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 40

API Used for this program:


1) ServletInputStream getInputStream( ) throws java.io.IOEception
Retrieves the body of the request as binary data
2) public static final String readUTF( ) throws IOException
Bytes are read from the contained input stream
JSP program source code:
<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%@ page import ="java.io.*" %>
<%
DataInputStream in = new DataInputStream((InputStream)request.getInputStream());
//
String theatre=in.readUTF();
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/movie","dayakar","");
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select * from movie where theatre='"+theatre+"'");
if(rs.next())
{
String message;
if(rs.getString(1).equals(theatre))
{
message = "Movie Name:"+rs.getString(2);
}
else
{
message = "Theatre Name Not Found";
}
out.println(message);
}
%>
Install Tomcat Server 6.0 and deploy this 'jsp' program in the following directory structure
webapps
|
|
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 41

----test5
|
|
-----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 MoviesMidlet extends MIDlet implements CommandListener {
Display display;
Form form;
TextField tf;
String str;
String url= "http://localhost:7000/test5/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 MoviesMidlet.Test test;
public MoviesMidlet() {}
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
form = new Form("Movie Information Retrieval");
tf = new TextField("Enter Theatre Name","",30,TextField.ANY );
form.append(tf);
form.addCommand(submit
form.addCommand(exit);
form.setCommandListener(this);
display.setCurrent(form);
}
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 42

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 MoviesMidlet.Test(this);
test.start();
test.setString(str);
}
}
class Test implements Runnable {
MoviesMidlet midlet;
private Display display;
String text
public Test(MoviesMidlet 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);

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 43

DataOutputStream os =(DataOutputStream)c.openDataOutputStream();
os.writeUTF(text.trim());
os.flush();
os.close();
// Get the response from the jsp 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 text and pass to jsp */
public void setString(String text) {
this.text = text;
}
/* Display 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 NEXT PAGE:

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 44

Android Introduction:
The goal of this is to learn the fundamentals of developing Android Applications, from
project creation to installation on a physical device. More specifically you should gain the
knowledge of how to use basic development tools to support the application development
process, as well as the key components of an Android application itself.
1. Setting Up the Development Environment
1.1 Download/Install the SDK:
Go to http://developer.android.com/sdk/index.html.
Unpack to a convenient location - Remember the full path to this location, we will
refer to it as <android_sdk_dir
1.2 Windows:
1. Right-click My Computer.
2. Click Properties.
3. Click Advanced tab.
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 45

4. Click Environment Variables button.


5. Double Click Path under System Variables.
6. Add ;<android_sdk_dir>/tools;
<android_sdk_dir>/platform-tools to the end of the Variable Values text field.
1.3 Download/Install the SDK Platform Components:
At the time of writing this lab there are eight different versions of the Android
Platform available, ranging from 1.1 to 2.2. It is best practice to develop for the oldest
platform available that still provides the functionality you need. This way you can be
assured that your application will be supported by as many devices as possible. However,
you will still want to download newer versions of the platforms so that you can test your
applications against these as well. Due to the size of each platform component you will
only be required to download and develop on one platform for the whole class. We will
target the highest platform that the G1 phones support, Android 1.6 (API 4).

Before we can begin developing we must download and install this platform:

Select the menu Window "Android SDK and AVD Manager", or click on the black
phone shaped icon in the toolbar.

Select Available Packages on the left hand side.

Expand the Google Android site in the "Site, Packages, and Archives" Tree.

Check the following items:


SDK Platform Android 1.6, API 4 Revision 3
Google APIs by Google Inc., Android API 4, Revision 2

Click Install Selected.

Accept the Terms for all packages and click Install Accepted.

We're now ready to develop our application.

2.1 Create a new Android Project


Open Eclipse.
Click the menu File New Project.
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 46

Expand the Android folder and select Android Project.


Name the project lab1<userID>
Fill in the Properties:
Application Name:-This is the friendly name of the application, that
Shows up on the device.
Package Name:-This is the namespace for the project, follows
Standard Java conventions.
Create Activity:-This optional field will automatically create a "Main
Activity" class for the project. You can think of the Main Activity as the
Home Page for your application.
Min SDK Version:-This specifies the minimum API Level on which your
application can run. By default this is set to the API Level of the Build
Target Platform. As new API's are added to newer Versions, their API
levels increase as well. A Program that uses an API Level of four won't
be able to run on a platform that has a lower API Level.
Click "Finish".
src: If you expand this out you'll see the package hierarchy you previously entered. This
is where your source code files will go. This is the auto-generated stub Activity Class
with the name you entered into the project creation wizard. We'll add some code to this
later.
Android 1.6: This is the version of the library you had chosen in the project creation
wizard. The application will be built using this version of 'android.jar'
res: This folder will contain all of the resources (a.k.a. external data files) that your
application may need. There are three main types of resources that you will be using and
the ADT has created a subdirectory for each.
drawable: This folder will hold image and animation files that you can use in your
application.
It already contains a file called icon.png which represents the icon that Android will use
for your application once it is installed
Layout: This folder will hold xml layout files that the application can use to construct
user interfaces. You will learn more about this later, but using a layout resource file is
the preferred way to layout your UI. It already contains a file called main.xml which
defines the user interface for Activity class. Double clicking on this file will open up
the Android UI Editor that you can use to help generate the xml layout files.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 47

values: This folder will hold files that contain value type resources, such as string and
integer constants. It already contains a file called strings.xml. Double clicking on this
file will open up the Android Resource Editor. Notice that there are two strings in there
already, one of which is named 'app_name'. If you select this value, on the right hand
side of the editor you should see the Application Name you entered in the project
creation wizard. You can use this editor to add new resources to your application.
gen: This folder will contain Java files that get auto-generated by ADT. Notice that it
already contains one file called "R.java".
R.java: This is a special static class that is used for referencing the data contained in
your resource files. If you open this file you will see a number of static inner classes for
each of the resource types, as well as static constant integers within them. Notice that
the names of the member variables are the same as the names of the values in your
resource files. Each value in a resource file is associated with an integer ID, and that ID
is stored in a member variable of the same name, within a static class named after its
data type. The 'app_name' resource value has an ID and is of value type 'string'. The
ADT automatically adds an integer constant to the R.string class and names it
'app_name'.
assets: This folder is for asset files, which are quite similar to resources. The main
difference being that anything stored in the 'assets' folder has to be accessed in the
classic 'file' manipulation style. For instance, you would have to use the Asset Manager
class to open the file, read in a stream of bytes, and process the data. You will not be
using assets quite as extensively as you will be using resources.
AndroidManifest.xml: Every project has a file with this exact name in the root
directory. It contains all the information about the application that Android will need to
run it: Package name used to identify the application. List of Activities, Services,
Broadcast receivers, and Content Provider classes and all of their necessary information,
including permissions. System Permissions the application must define in order to make
use of various system resources, like GPS. Application defined permissions that other
applications must have in order to interact with this application. Application profiling
information. Libraries and API levels that the application will use.
default. Properties: This file contains all of the project settings, such as the build target
you chose in the project creation wizard. If you open the file, you should see 'target=4',
which is your build target. You should never edit this file manually. If you wish to edit
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 48

the project properties, do so by right-clicking the project in the 'Package Explorer' panel,
and selecting 'Properties'.

3. Running on the Emulator:


3.1 On the Emulator:
Before we can run the application, we need to setup an Android Virtual Device (AVD), or
emulator, to run it on:
Select the menu Window "Android SDK and AVD Manager, or click on the black
phone shaped icon in the toolbar.
Select Virtual Devices on the left hand side.
Click the New... button.
Give your AVD a name.
Select the target build that we would like to run the application on, "Android 1.6 - API
Level 4".
Click Create AVD and close out the SDK/AVD Manager.
We're now ready to run our application.
Select the menu Run Run.
Note: The emulator may take a long time to start up.
Note: Another way to run your application is to right-click on the project in
the Package Explorer, then select Run as Android Application.
You can interact with the emulator using the mouse just like you would with a device.
To get started, press the Menu key to see the home screen.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 49

9. Write an Android application program that displays Hello World using Terminal.
To create a simple Hello World Android project can be done either with Eclipse or Android
Studio. Here I am going to explain how it can be created by using Android Studio 0.8.0.
Android Studio:
Studio can be downloaded from the below link.
http://tools.android.com/download/studio/beta
Pre-requisite:
Ensure appropriate JDK version is installed.
Download appropriate Android SDK based on the version we are developing.

Create new project:


MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 50

First step load Android Studio. Click on the New project

Configure the New Project:


Enter the application and company domain and select the project location as shown below and
click on Next button.

Select form factor:


Select the appropriate minimum version of android we are going to target as shown in the list as
below.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 51

Select the Activity:


Select the template need as pre requirement. I have selected the blank activity.

The class will be created based on the Activity Name entered.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 52

Click on the finish button. The project gets created and will be shown as below

Files /
Components
Important
files and
directory of
Android
project to be
known and
their purpose
1. src

This
contains the .java source files for your project. By default, it includes an

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 53

MainActivity.java source file having an activity class that runs when your app is launched
using the app icon.
2. generated - This contains the .R file, a compiler-generated file that references all the
resources found in your project. You should not modify this file
3. bin - This folder contains the Android package files .apk built by the ADT during the
build process and everything else needed to run an Android application.
4. res/drawable-hdpi - This is a directory for drawable objects that are designed for highdensity screens.
5. res/layout - This is a directory for files that define your app's user interface.
6. res/values - This is a directory for other various XML files that contain a collection of
resources, such as strings and colors definitions.
7. AndroidManifest.xml - This is the manifest file which describes the fundamental
characteristics of the app and defines each of its components.

String file:
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 54

The strings.xml file is located in the res/values folder and it contains all the text that your
application uses. For example, the names of buttons, labels, default text, and similar types of
strings go into this file. This file is responsible for their textual content. For example, a default
strings file will look like as following file.
R file:
The gen/myapps.helloworld/R.java file is the glue between the activity Java files like
Main.java and the resources like strings.xml. It is an automatically generated file and you should
not modify the content of the R.java file. Following is a sample of R.java file.

Layout File:
The activity_main.xml is a layout file available in res/layout directory, that is referenced
by your application when building its interface. You will modify this file very frequently to
change the layout of your application. For your "Hello World!" application, this file will have
following content related to default layout.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 55

Text Mode

Layout
Design

Running
app on
Emulator
Emulator
takes more
time to
load so before running app we should start emulator. Emulator can be started from SDK manager
tools Manage AVDs.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 56

AVD Manager
Create the AVD and click on the start to run the emulator

Once emulator is started it will get loaded by creating an AVD Manager

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 57

10. Write an Android application program that displays Hello World using Eclipse.
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 58

Aim: To write an Android application program that displays Hello World using Eclipse.
Implementation:
Step1: Open Eclipse.
Step2: Click the menu File --> New Project.

Step3:
Expand the Android folder and select Android Project.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 59

Step4:
i)

Name the project as week10.

Fill in the Properties:


Application Name = helloworld.This is the friendly name of the application, that shows up on the
device.
Package Name = com.cse.view. This is the namespace for the project, follows standard Java
conventions.
Create Activity = helloworld. This optional field will automatically create a "Main Activity"
class for the project. You can think of the Main Activity as the Home Page for your application.
Min SDK Version = 8.This specifies the minimum API Level on which your application
can run. By default this is set to the API Level of the Build Target Platform. As new API's are
added to newer Versions, their API levels increase as well. A Program that uses an API Level of
four wont be able to run on a platform that has a lower API Level.
v) Click "Finish".

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 60

Step5:
The resources for an Android project are stored in the res folder of your project hierarchy, which
includes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resources to provide design time access to them through the R variable .
The following code snippet shows the UI layout defined in the main.xml file created by the
Android.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 61

Defining UI in XML and inflating it is the preferred way of implementing your user interfaces;
asset neatly decouples your application logic from your UI design.
The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, we can also code them manually. Lets take a look at this file:
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android: layout_height="wrap_content"
android: text="@string/hello" />
</LinearLayout>
//values/strings.xml//
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">HelloWorld</string>
<string name="hello">Hello World, HelloWorld! </string>
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 62

</resources>
HelloWorld.java
package com.cse.view;
import android.app.Activity;
import android.os.Bundle;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Execution:
To execute application right-clickon the project in the Package Explorer, then select Run As
Android Application

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 63

View the list of installed applications in the emulator and find the helloworld application

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 64

11. Write an Android application program that accepts a name from the user and displays the
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 65

hello name to the user in response as output using Eclipse.


Aim: To 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.
Step1: Open Eclipse.
Step2: Click the menu File -> New -> Project.

Step3:
Expand the Android folder and select Android Project.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 66

Step4:
i)

Name the project as week11

ii) You can change the location of where you would like to save the project by un-selecting
the Default Location" check box, and supplying your own location.
iii) Check "Android 2.2" from the Build Target
Fill in the Properties:
Application Name = stringdisplay.This is the friendly name of the application, thats hows up on
the device.
Package Name = com.cse.view. This is the namespace for the project, followsstandard Java
conventions.
Create Activity = stringdisplay. This optional field will automatically create a "MainActivity"
class for the project. You can think of the Main Activity as the Home Page for your application.
Min SDK Version = 8.
iv)Click finish.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 67

Step5:
The resources for an Android project are stored in the res folder of your project hierarchy, which
includes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resources to provide design time access to them through the R variable.
The following code snippet shows the UI layout defined in the main.xml file created by the
Android

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 68

The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, We can also code them manually . Lets take a look at this file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<EditText
android:text=""
android:id="@+id/EditText01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
<Button android:text="send"
android:id="@+id/Button01"
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 69

android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
Step6:
projects src/ directory contains the standard Java-style tree of directories based upon the Java
package you used when you created the project resulted in src/com/cse/view/. Inside the
innermost directory you should find a regenerated source file named stringdisplay.java, which is
where your first activity will go.

package com.cse.view;
import android.view.View;
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 70

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.os.Bundle;
public class stringdisplay extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn=(Button)findViewById(R.id.Button01);
final EditText et=(EditText)findViewById(R.id.EditText01);
btn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String s=et.getText().toString();
Toast.makeText(getApplicationContext(),"welcome to"+s,100).show();
}
});
}
}
Execution:
To execute application right-click on the project in the Package Explorer, then select Run As->
Android application

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 71

View the list of installed applications in the emulator and find the stringdisplay application

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 72

12. Write an Android application program that demonstrates the following:


MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 73

(i) LinearLayout
(ii) RelativeLayout
(iii) TableLayout
(iv) GridView layout
(i) Aim: To Write an Android application program that demonstrates LinearLayout
Implementation:
Step1:Open Eclipse.
Step2:Click the menu File New Project.

Step3:
Expand the Android folder and select Android Project.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 74

Step4:
i) Name the project as week12_1
ii) You can change the location of where you would like to save the project by un-selecting
the "Default Location" check box, and supplying your own location.
iii) Check "Android 2.2" from the Build Target
iv) Fill in the Properties:
Application Name = linear layout. This is the friendly name of the application that shows
up on the device.
Package Name = com.cse.iew. This is the namespace for the project, follows standard
Java conventions.
Create Activity = lineralayout. This optional field will automatically create a
"MainActivity" class for the project. You can think of the Main Activity as the Home Page for
your application.
Min SDK Version = 8.
v) Click "Finish".

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 75

Step5:
The resources for an Android project are stored in the res folder of your project hierarchy, which
includes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resources to provide design time access to them through the R variable.
The following code snippet shows the UI layout defined in the main.xml file created by the
Android

The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, We can also code them manually . Lets take a look at this file:
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 76

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RadioGroup android:id="@+id/orientation"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5px">
<RadioButton
android:id="@+id/horizontal"
android:text="horizontal" />
<RadioButton
android:id="@+id/vertical"
android:text="vertical" />
</RadioGroup>
<RadioGroup android:id="@+id/gravity"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5px">
<RadioButton
android:id="@+id/left"
android:text="left" />
<RadioButton
android:id="@+id/center"
android:text="center" />
<RadioButton
android:id="@+id/right"
android:text="right" />
</RadioGroup>
</LinearLayout>
Step6:
projects src/ directory contains the standard Java-style tree of directories based upon the Java
package you used when you created the project resulted in src/com/cse/iew/. Inside the
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 77

innermost directory you should find a pregenerated source file named lineralayout.java, which is
where your first activity will go.

package com.cse.iew;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 78

import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.RadioGroup;
public class LinearLayout extends Activity {
private static final int HORIZONTAL = 0;
private static final int VERTICAL = 0;
private RadioGroup gravity;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RadioGroup orientation = (RadioGroup) findViewById(R.id.orientation);
orientation.setOnClickListener((OnClickListener) this);
gravity=(RadioGroup)findViewById(R.id.gravity);
gravity.setOnLongClickListener((OnLongClickListener) this);
}
@SuppressWarnings("null")
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioGroup orientation = null;
if(group==orientation) {
if(checkedId==R.id.horizontal) {
orientation.setOrientation(LinearLayout.HORIZONTAL);
}
else{
orientation.setOrientation(LinearLayout.VERTICAL);
}
}
else if (group==gravity) {
if(checkedId==R.id.left) {
gravity.setGravity(Gravity.LEFT);
}
else if (checkedId==R.id.center) {
gravity.setGravity(Gravity.CENTER_HORIZONTAL);
}
else if (checkedId==R.id.right) {
gravity.setGravity(Gravity.RIGHT);
}
}
}
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 79

}
Execution:
To execute application right-click on the project in the Package Explorer, then select Run
AsAndroid application

View the list of installed applications in the emulator and find the linerarlayout application

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 80

If we toggle the left radio button, the bottom RadioGroup adjusts to match

If we toggle the Center radio button, the bottom RadioGroup adjusts to match.
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 81

If we toggle the Right radio button, the bottom RadioGroup adjusts to match

(ii)Aim: To Write an Android application program that demonstrates RelativeLayout

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 82

Implementation:
Step1:Open Eclipse.
Step2:Click the menu File -> New -> Project.

Step3:
Expand the Android folder and select Android Project.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 83

Step4:
i) Name the project as Rel
ii)You can change the location of where you would like to save the project by un-selecting
the "Default Location" check box, and supplying your own location.
iii) Check "Android 2.2" from the Build Target
iv)Fill in the Properties:
Application Name =relativelayout .This is the friendly name of the application, that
shows up on the device.
Package Name = com.view.rl. This is the namespace for the project, follows standard
Java conventions.
Create Activity = Relative. This optional field will automatically create a "MainActivity"
class for the project. You can think of the Main Activity as the Home Page for your application.
Min SDK Version = 8.
v) Click "Finish".

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 84

Step5:
The resources for an Android project are stored in the res folder of your project hierarchy, which
includes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resources to provide design time access to them through the R variable .
The following code snippet shows the UI layout defined in the main.xml file created by the
Android

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 85

The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, we can also code them manually .Lets take a look at this file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter email address" />
<EditText
android:id="@+id/inputEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/label" />
<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 86

android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@id/inputEmail"
android:layout_marginRight="10px"
android:text="Login" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/btnLogin"
android:layout_toRightOf="@id/btnLogin"
android:text="Cancel" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Register" />
</RelativeLayout>
RelativeLayoutExampleActivity.java
package com.cse.view;
import android.app.Activity;
import android.os.Bundle;
public class RelativeLayoutExampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Execution:
To execute application right-click on the project in the Package Explorer, then select Run As->
Android

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 87

View the list of installed applications in the emulator and find the relativelayout application

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 88

(iii)Aim:To Write an Android application program that demonstrates Grid View Layout.
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 89

Implementation:
Step1:Open Eclipse.
Step2:Click the menu File -> New -> Project.

Step3:
Expand the Android folder and select Android Project.

Step4:
i) Name the project as gridview
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 90

ii) You can change the location of where you would like to save the project by un-selecting
the "Default Location" check box, and supplying your own location.
iii) Check "Android 2.2" from the Build Target
iv) Fill in the Properties:
Application Name =tab .This is the friendly name of the application, that shows up on the
device.
Package Name = com.view.layout. This is the namespace for the project, follows standard
Java conventions.
Create Activity = sim. This optional field will automatically create a "MainActivity" class
for the project. You can think of the Main Activity as the Home Page for your application.
Min SDK Version = 8.
vi)click finish

Step5:

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 91

The resources for an Android project are stored in the res folder of your project hierarchy, which
includes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resources to provide design time access to them through the R variable .
The following code snippet shows the UI layout defined in the main.xml file created by the
Android

Defining UI in XML and inflating it is the preferred way of implementing your user interfaces,
asit neatly decouples your application logic from your UI design.
The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, We can also code them manually .
Lets take a look at this file:

<?xml version="1.0" encoding="utf-8"?>


MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 92

<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1">
<TableRow>
<TextView
android:text="URL:" />
<EditText android:id="@+id/entry"
android:layout_span="3"/>
</TableRow>
<View
android:layout_height="2px"
android:background="#0000FF" />
<TableRow>
<Button android:id="@+id/cancel"
android:layout_column="2"
android:text="Cancel" />
<Button android:id="@+id/ok"
android:text="OK" />
</TableRow>
</TableLayout>

Execution:

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 93

To execute application right-clickon the project in the Package Explorer, then select Run As->
Android Application

View the list of installed applications in the emulator and find the tabapplication

Open tabapplication.You could see an activity screen like the one shown in figure
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 94

(iv)Aim: To Write an Android application program that demonstrates Grid View Layout.
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 95

Implementation:
Step1: Open Eclipse.
Step2: Click the menu File -> New -> Project.

Step3:
Expand the Android folder and select Android Project.
Step4:
i) Name the project as gridview
ii)You can change the location of where you would like to save the project by un-selecting
the "Default Location" check box, and supplying your own location.
iii) Check "Android 2.2" from the Build Target List. This identifies that the project is being built
to be compatible with Android versions 2.2 and later. Its generally preferred that you choose the
lowest build number possible, so as to be compatible with the largest number of existing systems
in place. This build target can be changed any time later on through the Project Properties menu.
iv) Fill in the Properties:
Application Name =tab .This is the friendly name of the application, that shows up on the
device.
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 96

Package Name = com.view.layout. This is the namespace for the project, follows standard
Java conventions.
Create Activity = sim. This optional field will automatically create a "Main Activity"
class for the project. You can think of the Main Activity as the Home Page for your application.
Min SDK Version = 8.This specifies the minimum API Level on which your application
can run. By default this is set to the API Level of the Build Target Platform. As new API's are
added to newer Versions, their API levels increase as well. A Program that uses an API Level of
four wont be able to run on a platform that has a lower API Level.
v) Click "Finish".

Step5:
The resources for an Android project are stored in the res folder of your project hierarchy,
whichincludes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resourcesto provide design time access to them through the R variable .
The following code snippet shows the UI layout defined in the main.xml file created by the
Android
Defining UI in XML and inflating it is the preferred way of implementing your user interfaces,
asit neatly decouples your application logic from your UI design.
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 97

The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, We can also code them manually . Lets take a look at this file:
Main.xml
<?xmlversion="1.0"encoding="utf-8"?>
<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<GridView
android:id="@+id/GridView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="50px"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
>
</GridView>
</RelativeLayout>

HelloWorld.java
package com.view.basics;
import android.app.Activity;
import android.os.Bundle;
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 98

import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
public class HelloWorld extends Activity {
GridView gridView;
static final String[] num=new String[]{
"A","B","C","D","E",
"F","G","H","I","J",
"K","L","M","N","O",
"P","Q","R","S","T",
"U","V","W","X","Y","Z"
};
protected static final String TextView = null;

/** Called when the activity is first created. */


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridView=(GridView)findViewById(R.id.GridView01);
ArrayAdapter<String>adapter=new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,num);
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 99

gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View v, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), ((TextView)
v).getText(),Toast.LENGTH_SHORT).show();
}
});
}
}
OnItemClickListener.java
package com.view.basics;
public interface OnItemClickListener extends android.widget.AdapterView.OnItemClickListener
{
}

Execution:
To execute application right-clickon the project in the Package Explorer, then select Run As->
Android Application
You could see an activity screen like the one shown in figure:

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 100

13. Write an Android application program that converts the temperature in Celsius to
Fahrenheit.
Aim: To write an Android application program that converts the temperature in Celsius to
Fahrenheit.
Implementation:
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 101

Step1: Open Eclipse.


Step2:Click the menu File -> New -> Project.

Step3:
Expand the Android folder and select Android Project.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 102

Step4:
i) Name the project as week13
ii) You can change the location of where you would like to save the project by un-selecting
the "Default Location" check box, and supplying your own location.
iii) Check "Android 2.2" from the Build Target List. This identifies that the project is being built
to be compatible with Android versions 2.2 and later. Its generally preferred that you choose the
lowest build number possible, so as to be compatible with the largest number of existing systems
in place. This build target can be changed any time later on through the Project Properties menu.
iv) Fill in the Properties:
Application Name = converter.This is the friendly name of the application, that shows up on the
device.
Package Name = com.view.cse. This is the namespace for the project, follows standard Java
conventions.
Create Activity = week13. This optional field will automatically create a "Main Activity" class
for the project. You can think of the Main Activity as the Home Page for your application.
Min SDK Version = 8.This specifies the minimum API Level on which your application can run.
By default this is set to the API Level of the Build Target Platform. As new API's are added to
newer Versions, their API levels increase as well. A Program that uses an API Level of four
wont be able to run on a platform that has a lower API Level.
v) Click "Finish".

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 103

Step5:
The resources for an Android project are stored in the res folder of your project hierarchy, which
includes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resources to provide design time access to them through the R variable .
The following code snippet shows the UI layout defined in the main.xml file created by the
Android

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 104

Defining UI in XML and inflating it is the preferred way of implementing your user interfaces,
as it neatly decouples your application logic from your UI design.
The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, we can also code them manually. Lets take a look at this file:
<? xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 105

/>
<EditTextandroid:text="@+id/EditText01"
android:id="@+id/EditText01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
<Button android:text="@+id/Button01"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
It uses LinearLayout as a layout container for a TextView that displays the Hello
Worldgreeting.A string resource containing the display text has been placed into the
res\values\strings.xml file. The value is named 'hello. The Edit Text widget, which is a subclass
of the TextView used for labels. The default text in this label is null. Button is an Androidsupplied widget. Because we want to reference this button from our Java code, we need to give it
an identifier via the android: id attribute.android: text indicates the initial text to be displayed on
the button face (in this case, the string is convert) android:layout_width and
android:layout_height tell Android to have the buttons width and height fill the parent, in this
case the entire screen.
Step6:
projects src/ directory contains the standard Java-style tree of directories based upon the Java
package you used when you created the project resulted in src/com/vignan/cse/. Inside the
innermost directory you should find a pre generated source file named week13.java, which

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 106

activity is the base class for the visual, interactive components of your application; it is roughly
equivalent to a Form in traditional desktop development. The following snippet shows the
skeleton code for an Activity-based class.
package com.view.cse;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class week13extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 107

setContentView(R.layout.main);
Button btn=(Button)findViewById(R.id.Button01);
final EditText et=(EditText)findViewById(R.id.EditText01);
btn.setOnClickListener(newOnClickListener()
{
public void onClick(View v)
{
String s=et.getText().toString();
Float c=Float.parseFloat(s);
Double f=(c*1.8)+32;
Toast.makeText(getApplicationContext(),"TEMPERTURE IN CELSIUS IS "+f,1000).show(); }
});
}
}
This activity contain, rather than instantiating the Button onCreate() callback, can reference the
one from the XML layout. The content view to be a view created in Java code, we set it to
reference the XML layout (setContentView (R.layout.main)). The R.java source file will be
updated when we rebuild this project to include a reference to our layout file (stored as main.xml
in our projects res/layout directory).
To get hands on our Button instance, use the findViewById() call. Since we identified our button
as @+id/button, we can reference the buttons identifier as R.id.button. Now, with the Button
instance in hand, we can set the callback and set the label as temperature in Fahrenheit.
Execution: To execute application right-click on the project in the Package Explorer, then select
Run As-> AndroidApplication

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 108

View the list of installed applications in the emulator and find the converter application

Open converter application.You could see an activity screen like the one shown in figure
Now, enter the temperature in Celsius in textbox.
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 109

Now,click on convert.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 110

Week14:
Aim:To Write an Android application program that demonstrates intent in mobile application
development.
Implementation:
Step1:Open Eclipse.
Step2:Click the menu File -> New -> Project.

Step3:
Expand the Android folder and select Android Project.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 111

Step4:
i)

Name the project as Intent

ii) You can change the location of where you would like to save the project by un-selecting
the "Default Location" check box, and supplying your own location.
iii) Check "Android 2.2" from the Build Target List. This identifies that the project is being built
to be compatible with Android versions 2.2 and later. Its generally preferred that you choose the
lowest build number possible, so as to be compatible with the largest number of existing systems
in place. This build target can be changed any time later on through the Project Properties menu.
iv) Fill in the Properties:
Application Name = Intent. This is the friendly name of the application, that shows up on
the device.
Package Name = com.intent.cse. This is the namespace for the project, follows standard
Java conventions.
Create Activity = first. This optional field will automatically create a "MainActivity"
class for the project. You can think of the Main Activity as the Home Page for your application.
Min SDK Version = 8.This specifies the minimum API Level on which your application
can run. By default this is set to the API Level of the Build Target Platform. As new API's are
added to newer Versions, their API levels increase as well. A Program that uses an API Level of
four wont be able to run on a platform that has a lower API Level.
v)Click "Finish".
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 112

Step5:
The resources for an Android project are stored in the res folder of your project hierarchy,
whichincludes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resourcesto provide design time access to them through the R variable .
The following code snippet shows the UI layout defined in the main.xml file created by the
Android

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 113

Defining UI in XML and inflating it is the preferred way of implementing your user
asset neatly decouples your application logic from your UI design.

interfaces;

The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, we can also code them manually. Lets take a look at this file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 114

<Button android:text="click here"


android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
It uses LinearLayout as a layout container for a TextView that displays the Hello World
greeting..A string resource containing the display text has been placed into the
res\values\strings.xml file. The value is named 'hello'. Button is an Android-supplied widget.
Because we want to reference this button from our Java code, we need to give it an identifier via
the android:id attribute. android: text indicates the initial text to be displayed on the button face
(in this case, the string is next) android:layout_width and android:layout_height tell Android to
have the buttons width and height fill the parent, in this case the entire screen.
Step6:
projects src/ directory contains the standard Java-style tree of directories based upon the Java
package you used when you created the project resulted in src/com/intent/cse/. Inside the
innermost directory you should find a pregeneratedsource file named first.java, which is where
your first activity will go.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 115

Activity is the base class for the visual, interactive components of your application; it is roughly
equivalent to a Form in traditional desktop development. The following snippet shows the
skeleton code for an Activity-based class.
package com.intent.cse;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class firstextends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bt=(Button) findViewById(R.id.Button01);
bt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent it=newIntent(Navigation.this,Second.class
startActivity(it);
}
});
}
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 116

}
This activity contain, rather than instantiating the Button onCreate () callback, can
reference the one from the XML layout. The content view to be a view created in Java code, we
set it to reference the XML layout (setContentView (R.layout.main)). The R.java source file will
be updated when we rebuild this project to include a reference to our layout file (stored as
main.xml in our projects res/layout directory).
To get hands on our Button instance, use the find ViewById() call. Since we identified our button
as @+id/button, we can reference the buttons identifier as R.id.button. Now, with the Button
instance, Intents encapsulate a request, made to Android, for some activity or other Intent
receiver to do something. Here the activity intend to launch is second.class.To call, startActivity
() with the Intentthis will cause Android to find the best-match activity and pass the Intent to it
for handling. Your activity will not be informed when the child activity is complete.
Step7:
The activity first.java intend to launch the activity second.java so, now second.java and
second.xml files need to be created as given below.
projects src/ directory contains the standard Java-style tree of directories based upon the Java
package you used when you created the project resulted in src/com/intent/cse/.Right click on the
package the select new->class.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 117

Enter the name of the class as second and click on finish.

projects src/ directory contains the standard Java-style tree of directories based uponthe Java
package you used when you created the project resultedin src/com/intent/cse/. Inside the
innermost directory you should find a pregeneratedsource file named second.java, which is
where your first activity will go.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 118

Activity is the base class for the visual, interactive components of your application; it is roughly
equivalent to a Form in traditional desktop development. The following snippet shows the
skeleton code for an Activity-based class.
package com.intent.cse;
import android.app.Activity;
import android.os.Bundle;
public class second extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
}
}

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 119

In this activity, the content view to be a view created in Java code, we set it to reference the
XML layout (setContentView (R.layout.second)). The R.java source file will be updated when
we rebuild this project to include a reference to our layout file (stored as second.xml in our
projects res/layout directory).
To create second.xml file right click on res then select new->other.

Expand the Android folder and select Android XML file and click on next.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 120

Enter the file name as second.xml and click on finish.

The resources for an Android project are stored in the res folder of your project hierarchy, which
includes draw able, layout, and values subfolders. The ADT plug-in interprets these XML
resources to provide design time access to them through the R variable .
The following code snippet shows the UI layout defined in the second.xml file created by the
Android

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 121

The xml UI layout has been added to res\layout\second.xml.We can use the Android Layout
Editor to create xml layout, we can also code them manually. Lets take a look at this file:
<? xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/icon">
</LinearLayout>
This XML layout sets default icon available in android2.2 as background.
Step8:
The activity second.java would need to be named in your AndroidManifest.xml file.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 122

The following shows the code defined in the AndroidManifest.xml file created by the Android:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.viiew.iintent"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Navigation"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 123

<activity android:name=".second"/>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
Execution:
To execute application right-click on the project in the Package Explorer, then select Run As->
Android Application

View the list of installed applications in the emulator and find the Intent application.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 124

Open Intent application.You could see an activity screen like the one shown in figure.

Now, on clicking the button next you could see an activity screen like the one shown in figure.

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 125

MOBILE APPLICATION DEVELOPMENT LAB RECORD

Page 126

Vous aimerez peut-être aussi