You are on page 1of 68

Department

Of
Computer Science and Engineering

MOBILE APPLICATION DEVELOPMENT

LABORATORY MANUAL

AVANTHI INSTITUTE OF ENGINEERING & TECHNOLOGY


Cherukupalli(V), Near Tagarapuvalasa Bridge, Bhogapuram(M),Vizianagaram(Dist).
08933-226739, www.avanthi.edu.in, www.avanthiportal.com,
Email:hodcse.avanthi@gmail.com

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Course Title:

MAD

Class:

B.Tech IV Year I Sem

Branch:

CSE

Regulation:

R10

No. of Hours/Week:

COURSE OBJECTIVES:
To impart fundamental concepts in the area of mobile computing.
To provide a computer systems perspective on the converging areas of wireless
networking, embedded systems, and software, and to introduce selected topics of current
research interest in the field.
To impart knowledge in wireless and mobile computing and in their applications.

COURSE OUTCOME:
Understanding the systems, protocols and mechanisms to support mobility for mobile
internet user.
Develop networked applications for mobile devices.
Understanding the hardware necessary to support mobility and computation
Understanding the possible applications of mobility to computation
Design and implement a novel mobile computing application

EQUIPMENT/SOFTWARE REQUIRED:
1. JDK and Java Wireless Toolkit must be installed on your system
2. Intel based desktop PC with minimum of 166MHZ
3. No. of Systems required 60 per sess

Prepared by: Mr. J.V.KIRAN


INDEX

H.O.D

Sl.No
1

6
7
8
9
10
11
12
13

Name of the Program


Write a J2ME application that shows how to change font size and color.
Write a J2ME program which creates following kind of menu
o Cut
o Copy
o Past
o Delete
o Select all
o Unselect all
Write J2ME program which creates following kind of
menu[Event Handling]
o Cut
can be on/off
o Copy
can be on/off
o Past
can be on/off
o Delete
can be on/off
o Select all
Put all four Options on
o Unselect all Put all four Options off
Create MIDP application which draws a bar graph to the display
data values can be given at int[]array. You can enter four data
integers values to the input text field
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)
Write a sample program to show how to make a socket connection
from J2ME phone
Authentication with a Web Server
Login to HTTP Server from a J2ME Program
Create a MIDP application, which show to the user 5-10 quiz
questions. All questions have 4 possible options and one right option
exactly. Application counts and shows to the user how many right
answers were right and shows them to user
Write an android application program that displays hello world using
Terminal
Write an android application program that displays hello world using
eclipse
Write an android application program that accepts input from the user
and displays the hello name to the user in response as output using
eclipse
Write an android application program that demonstrates different
layouts in android.
Write an android application program that converts the temperature
from Celsius to Fahrenheit.

Page.No
11

14

16

19

22

25
31
33
40
43
46
48
61

14

Write an android application that shows how to use intents in mobile


application development

64

Mobile Application Development


Manual

Laboratory

Introduction to J2ME
Installation of Java Wireless Toolkit (J2ME)
1) If the Java Development Kit (JDK) is not there or only having the Java Runtime
Environment (JRE) installed, install the latest JDK from
http://java.sun.com/javase/downloads/index.jsp.
.
2) Next, download the Java Wireless Toolkit (formerly called J2ME Wireless Toolkit)
from: http://java.sun.com/products/sjwtoolkit/download.html.
3) Run the installer (for example, for Windows it is: sun_java_wireless_toolkit- 2_5_2windows.exe). The installer checks whether a compatible Java environment has been preinstalled. If not, it is necessary to uninstall old versions of Java and perform Step 1 again.
J2ME applications using Wireless Tool Kit
To start, launch the java wireless toolkit from your desktop, then it window will appear
like this:

Click on the new project button beside the menu like below

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

A windows will appear, type the project name and the Midlet className, like in the window
below, we choose
project name: HelloworldProject
Midlet class name: Helloworldmidlet

Then another window called API selected will be show , for just make sure that you the
profile that is selected there, offer the most higher version of Midlet as Profile, and the CLDC
as configuration, choose the MSA as target profiles that give us Midlet 2.1 as profile and the
CLDC1.1 as configuration.
Then click on ok to validate and
you would get this message in the
sun java wireless toolkit window:
The message in the windows
above, said that the project have
been successfully created and the

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

folder bin, lib, res, src have been created in the appropriate folder of the project and the project
is already open at this time.
-Bin folder: Will content the executable file for your application(. Jar, .jad, Manifest) for a
real deployment,
-Lib folder: Will be where we would specify any extern library that we will use in our
mobile application.
-Src folder: Will be where the source file will be store.
-Res folder: Will content files like pictures that we want to include or use in our mobile
application.
Create the source code file :
. Create a new file and start typing the content of your java file in. Because your class will
inherit from a Midlet class, you must prior import the library that content the definition of the
Midlet like this .
import javax.microedition.midlet.*;
Now save the java file that is in your textpad editor in the src directory situated in the project
directory that has been created when you created your helloworldproject from the Wireless tool
kit,
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class HelloworldMidlet extends MIDlet {
private Form form;
private Display display;
public HelloworldMidlet() {
form = new Form("My First J2ME App");
String msg = "Hello World";
form.append(msg);
display = Display.getDisplay(this);
display.setCurrent(form);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
notifyDestroyed();
}
protected void pauseApp()
3

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

{
}
protected void startApp() throws MIDletStateChangeException
{
}
}

Launch the wireless toolkit emulator, then open your project by hitting the open project
button and go through the folders where your project have been saved , then select your project
name and hit openproject button like below:

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

You would get a screen like the screen-hot below:

Go to project click on run. The emulator will open, at this time the application is not yet
being executed, it shows a window with the name of your project like below:

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

To start the application , you must select the Launch button (bottom right of the emulator) to
run your mobile application Then you would get on your mobile emulator screen. a Hello World
message like below:

Example 1: J2ME applications creation using ECLIPSE:

STEP 1
To Create New J2ME Project
File -> New -> select j2me --> j2me Midlet suite -> click Next
6

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Give the project name as HelloworldMobileApp and click Next


In Midlet Suite Properties use the default settings.

Click Next and Finish.


Now you can see it create your project in Project area.
STEP 2
Now select the project right click it and New --> Other

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Select J2ME Midlet and click Next. Give a name for the midlet.
It create the HelloworldMidlet class and inherit the some methods.
Now add these following code.
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class HelloworldMidlet extends MIDlet
{
private Form form;
private Display display;
public HelloworldMidlet()
{
form = new Form("My First J2ME App");
String msg = "Hello World";
form.append(msg);
display = Display.getDisplay(this);
display.setCurrent(form);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
8

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

notifyDestroyed();
}
protected void pauseApp()
{
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException
{
// TODO Auto-generated method stub
}
}

STEP 3
We did finish coding now. But in order to run your app you have to do some configuration.
Right click the project --> Run as --> Run Configuration
Click Browse and select the project.

and Click Run


Now you can see it start the mobile device and show hello world.
9

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Exercise 1:
Write a J2ME application that shows how to change font size and color.
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;
10

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

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);
11

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

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:

12

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Exercise 2:
Write a J2ME program which creates following kind of menu
o Cut
o Copy
o Past
o Delete
o Select all
o Unselect all
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class MenuEvents extends MIDlet {
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;
13

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

public Item item;


public MenuEvents()
{
display=Display.getDisplay(this);
form=new Form("");
form1=new Form("Selcted Options are");
ch=new ChoiceGroup("Preferences",Choice.MULTIPLE);
ch.append("cut",null);
ch.append("copy",null);
ch.append("paste",null);
ch.append("delete",null);
ch.setSelectedIndex(1, true);
form.append(ch);
ch1=new ChoiceGroup("",Choice.EXCLUSIVE);
ch1.append("select all",null);
ch1.append("unselect all",null);
ch1.setSelectedIndex(1, true);
form.append(ch1);
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);
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
}
Output:

14

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Exercise 3:
Write J2ME program which creates following kind of menu[Event Handling]
o Cut
can be on/off
o Copy
can be on/off
o Past
can be on/off
o Delete
can be on/off
o Select all
Put all four Options on
o Unselect all Put all four Options off
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class MenuEvents2 extends MIDlet implements CommandListener,ItemStateListener {
15

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

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 MenuEvents2()
{
display=Display.getDisplay(this);
form=new Form("");
form1=new Form("Selcted Options are");
ch=new ChoiceGroup("Preferences",Choice.MULTIPLE);
ch.append("cut",null);
ch.append("copy",null);
ch.append("paste",null);
ch.append("delete",null);
ch.setSelectedIndex(1, true);
form.append(ch);
ch1=new ChoiceGroup("",Choice.EXCLUSIVE);
ch1.append("select all",null);
ch1.append("unselect all",null);
ch1.setSelectedIndex(1, true);
form.append(ch1);
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)
16

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

{
}
public void commandAction(Command command,Displayable displayable)
{
if(displayable==form)
{
if(command==View)
{
boolean opt[]=new boolean[ch.size()];
options=new StringItem("","");
String values="";
ch.getSelectedFlags(opt);
options.setText("");
for(int i=0;i<opt.length;i++)
{
if(opt[i])
{
values+=ch.getString(i)+"\n";
}
}
options.setText(values);
form1.append(options);
display.setCurrent(form1);
}
else if(command==Exit)
{
destroyApp(true);
notifyDestroyed();
}
}
else if(displayable==form1)
{
if(command==Back)
{
display.setCurrent(form);
options.setText("");
}
}
}
public void itemStateChanged(Item item)
{
if(item==ch1)
{
int i=0;
17

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

int size=ch.size();
while(i<size)
{
if(ch1.getSelectedIndex()==0)
ch.setSelectedIndex(i, true);
else
ch.setSelectedIndex(i, false);
i++;
}
}
}
}
Output:

Exercise 4:
Create MIDP application which draws a bar graph to the display data values can be
given at int[]array. You can enter four data integers values to the input text field.
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;
18

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

public TextField textfield4;


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);
form.append(textfield1);
form.append(textfield2);
form.append(textfield3);
form.append(textfield4);
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[4];
data[0]=Integer.parseInt(textfield1.getString());
data[1]=Integer.parseInt(textfield2.getString());
data[2]=Integer.parseInt(textfield3.getString());
data[3]=Integer.parseInt(textfield4.getString());
d=new BarCanvas(data);
d.addCommand(backCommand);
19

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

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 , h);
x+=30;
i++;
}
}
}
Output:
20

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Exercise 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)
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()
{
21

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

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(' ', '.');
int len=s.length();
int i=0;
int c=0;
String s1="";
while(i<len)
{
if(s.charAt(i)=='.')
{
if(c==0)
{
22

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

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);
}
}
}
Output:

23

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Exercise 6:
Write a sample program to show how to make a socket connection from J2ME phone.
Creating the Datagram Server project
1) Click on Wireless Toolkit 2.5.2 under the group: All ProgramsSun Java
(TM) Wireless Toolkit 2.5.2.
2) Click on 'New Project...' button.
24

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

3) Enter project name as 'DatagramServer'. Enter MIDlet name as 'DatagramServer'. Note that
the Midlet name is the same as the name of the class in the source code, which extends the
MIDlet class, otherwise the application wont run.
4) Another window pops up where it is required to select a target platform. Select 'MIDP 1.0'
from the drop down list.
5) After clicking OK, the project is created; and the Wireless Toolkit tells that the name of the
folder where source code files are created. The path of the source code folder is displayed in the
debug output window.
Creating and Compiling the DatagramServer source files
The Wireless Toolkit does not come with an IDE by default so Use any IDE or a text editor
like Notepad.
1) Create a new text file called DatagramServer.java in the source folder of the project. The
exact path of this folder is displayed in the Wireless Toolkit window.
2) Paste contents DatagramServer.java from into the source file.
Running your Server application on the Phone simulator
1) After compiling the project successfully, click on the Run button in the Wireless Toolkit
window.
2) A graphical window depicting a phone handset will appear with the name of your application
highlighted on its screen as shown below.
3) To start the application, click on the right soft-key (marked with a dot) below the
Launch command.
4) The phone simulator might ask if it is OK to run the network application. Select Yes by
clicking on the appropriate soft-key. The server is now up and running.
5) Keep the server running during the creation, compilation and running of the Datagram Client
application.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
public class DatagramServer extends MIDlet implements CommandListener
{
25

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

public Form form1;


public Form form2;
public Command startCommand;
public Command refreshCommand;
public Command exitCommand;
public Display display;
public StringItem st;
public DatagramServer()
{
display=Display.getDisplay(this);
startCommand=new Command("Start",Command.OK,1);
refreshCommand=new Command("Refresh",Command.OK,1);
exitCommand=new Command("Exit",Command.EXIT,1);
st=new StringItem(" "," ");
form1 =new Form("DataGramserver");
form2=new Form("Ready to receive Messages");
form1.addCommand(startCommand);
form1.setCommandListener(this);
form2.addCommand(refreshCommand);
form2.addCommand(exitCommand);
form2.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form1);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command cmd,Displayable displayable)
{
if(displayable==form1)
{
if(cmd==startCommand)
{
try {
DatagramConnection dgc = (DatagramConnection)
Connector.open("datagram://:9001");
try {
26

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

int size = 100;


Datagram datagram = dgc.newDatagram(size);
dgc.receive(datagram);
form2.append(datagram.getData().toString());
} finally {
dgc.close();
}
} catch (Exception x)
{
x.printStackTrace();
}

display.setCurrent(form2);
}
}
else if(displayable==form2)
{
if(cmd==exitCommand)
{
notifyDestroyed();
}
else if(cmd==refreshCommand)
{
st.setText(" ");
}
}
}
}

Creating the DatagramClient project


1) Use the same instance of the Wireless Toolkit that is used for creating and compiling the
Datagram Server project.
2) Click on 'New Project...' button.
27

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

3) A new window pops up. Enter project name as 'DatagramClient'. Enter MIDlet name as
'DatagramClient'. Note that the Midlet name is the same as the name of the class in the source
code, which extends the MIDlet class.
4) Another window pops up where one has to select a target platform. Select 'MIDP 1.0' from
the drop down list.
5) After clicking OK, the project is created and the Wireless Toolkit tells where to place the
source code files. The path of the source code folder is displayed in the debug output window as
explained before.
Creating and Compiling the DatagramClient source files
1) Create a new text file called DatagramClient.java in the source folder of the
project.
2) Paste contents DatagramClient.java into the source file.
3) Then click on the Build button in the Wireless Toolkit window. If the compilation is OK, it
will say Build Complete in the window's debug output window, otherwise it will show the
errors. Note: In the source code, use the System.out.println() statement to output debug
information to this window.
Running your Client application on the Phone simulator
1) After compiling the project successfully, click on the Run button in the Wireless Toolkit
window.
2) A graphical window depicting a phone handset will appear with the name of the application
highlighted on its screen.
3) To start the application, click on the right soft-key (marked with a dot) below the Launch
command.
4) The phone simulator might ask if it is OK to run the network application. Select Yes by
clicking on the appropriate soft-key. The client is now up and running.
5) When the client executes on the phone simulator, one should see a text box with the caption
'Message'. Enter any message and press the right soft-key (corresponding to Send). If the clientserver application is working properly, the screen of the server phone will display the message
sent by the client and the client screen will now display a message sent by the server in response.
The response message from the server is the original client message in reverse.
28

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

6) Try various features of the phone simulator including the different look-and feel options.
Source code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
public class DatagramClient extends MIDlet implements CommandListener
{
public Form form1;
public Display display;
public TextField textfield;
public Command sendCommand;
public DatagramClient()
{
display=Display.getDisplay(this);
form1=new Form("Datagram Client");
sendCommand=new Command("send",Command.OK,1);
textfield=new TextField("Enter Text",null,30,TextField.ANY);
form1.append(textfield);
form1.addCommand(sendCommand);
form1.setCommandListener(this);
}
public void startApp() {
display.setCurrent(form1);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command cmd,Displayable d)
{
if(cmd==sendCommand)
{
try
{
DatagramConnection dgc = (DatagramConnection)
Connector.open("datagram://localhost:9001");
try {
while(true)
{
29

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

byte[] payload = textfield.getString().getBytes();


Datagram datagram = dgc.newDatagram(payload, payload.length);
dgc.send(datagram);
}
} finally
{
dgc.close();
}
} catch (Exception x)
{
x.printStackTrace();
}
}
}
}
Output:

Exercise 7:
Authentication with a Web Server
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.
Source Code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class login extends MIDlet implements CommandListener
{
public Form form1;
30

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

public Command okCommand;


public Display display;
public HttpConnection ht=null;
public InputStream ist=null;
public StringItem st;
public TextField t1;
public TextField t2;
public Alert alert;
public Form form2;
public login()
{
display=Display.getDisplay(this);
st=new StringItem(" "," Welcome");
alert =new Alert(" ","Wrong UserName or Password",null,AlertType.INFO); t1=new
TextField("UserName"," ",30,TextField.ANY);
t2=new TextField("Password"," ",30,TextField.PASSWORD);
form1=new Form("Login Here");
form2=new Form("Welcome");
okCommand=new Command("Login",Command.OK,1);
form1.addCommand(okCommand);
form1.setCommandListener(this);
form1.append(t1);
form1.append(t2);
form2.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)
31

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

{
try
{
String
url="http://192.168.5.19:8080/WebApplication7/index.jsp?t1="+t1.getString().trim()
+"&t2="+t2.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("ok")) Dept
display.setCurrent(form2);
else
{
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
catch(Exception ex)
{
form1.append(ex.toString());
}}}}
Exercise 8
Create a MIDP application, which show to the user 5-10 quiz questions. All questions have
4 possible options and one right option exactly. Application counts and shows to the user
how many right answers were right and shows them to user
Source Code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.io.*;
public class Quiz extends MIDlet implements CommandListener
{
public Form form1;
public Form form2;
public Form form3;
public Form form4;
public Form form5;
32

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

public Form form6;


public Form form7;
public ChoiceGroup ch1;
public ChoiceGroup ch2;
public ChoiceGroup ch3;;
public ChoiceGroup ch4;;
public ChoiceGroup ch5;;
public Command nextCommand;
public Command backCommand;
public Command MenuCommand;
public Command OkCommand;
public Command ExitCommand;
public Command sCommand;
public Display display;
public StringItem st;
public TextField textfield;
public int count;
public RecordStore recordstore=null;
public RecordEnumeration re=null;
public Alert alert;
public StringItem st1;
public Quiz()
{
count=0;
display=Display.getDisplay(this);
nextCommand=new Command("Next",Command.OK,1);
backCommand=new Command("Back",Command.BACK,1);
st1=new StringItem("","");
textfield=new TextField("EnterName","",20,TextField.ANY);
form1=new Form("J2ME Stands for");
form2=new Form("a+b=");
form3=new Form("5*5");
form4=new Form("Who is AP CM");
form5=new Form("How many Districts in AP");
form6=new Form("Score");
ch1=new ChoiceGroup("",Choice.EXCLUSIVE);
ch1.append("Java 2 Mobile Edition", null);
ch1.append("Java 2 Macro Edition", null);
ch1.append("Java 2 Micro Edition", null);
ch1.append("Java 2 Music Edition", null);
form1.append(ch1);
33

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

form1.addCommand(nextCommand);
form1.setCommandListener(this);
ch2=new ChoiceGroup("",Choice.EXCLUSIVE);
ch2.append("b+a", null);
ch2.append("b*a", null);
ch2.append("b/a", null);
ch2.append("b-a", null);
form2.append(ch2);
form2.addCommand(nextCommand);
form2.addCommand(backCommand);
form2.setCommandListener(this);
ch3=new ChoiceGroup("",Choice.EXCLUSIVE);
ch3.append("20", null);
ch3.append("30", null);
ch3.append("10", null);
ch3.append("25", null);
form3.append(ch3);
form3.addCommand(nextCommand);
form3.addCommand(backCommand);
form3.setCommandListener(this);
ch4=new ChoiceGroup("",Choice.EXCLUSIVE);
ch4.append("Rosiah", null);
ch4.append("Jagan", null);
ch4.append("ChandaBabu", null);
ch4.append("Kiran", null);
form4.append(ch4);
form4.addCommand(nextCommand);
form4.addCommand(backCommand);
form4.setCommandListener(this);
ch5=new ChoiceGroup("",Choice.EXCLUSIVE);
ch5.append("8", null);
ch5.append("4", null);
ch5.append("11", null);
ch5.append("23", null);
form5.append(ch5);
form5.addCommand(backCommand);
form5.addCommand(nextCommand);
34

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

form5.setCommandListener(this);
form6.addCommand(ExitCommand);
}
public void startApp()
{
display.setCurrent(form1);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command cmd,Displayable displayable)
{
if(displayable==form1)
{
if(cmd==nextCommand)
display.setCurrent(form2);
}
else if(displayable==form2)
{
if(cmd==nextCommand)
display.setCurrent(form3);
else if(cmd==backCommand)
display.setCurrent(form1);
}
else if(displayable==form3)
{
if(cmd==nextCommand)
display.setCurrent(form4);
else if(cmd==backCommand)
display.setCurrent(form2);
}
else if(displayable==form4)
{
if(cmd==nextCommand)
display.setCurrent(form5);
else if(cmd==backCommand)
display.setCurrent(form3);
}
35

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

else if(displayable==form5)
{
if(cmd==nextCommand)
{
if(ch1.getSelectedIndex()==2)
count++;
if(ch2.getSelectedIndex()==0)
count++;
if(ch3.getSelectedIndex()==3)
count++;
if(ch4.getSelectedIndex()==3)
count++;
if(ch5.getSelectedIndex()==3)
count++;
st.setText(String.valueOf(count));
form6.append(st);
form6.append(textfield);
display.setCurrent(form6);
}
}
}
}
Output:

36

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

ANDROID
1. Introduction
Android is an Operating System for mobile devices developed by Google, which is built upon
Linux kernel. Android competes with Apple's iOS (for iPhone/iPad), RIM's Blackberry,
Microsoft's Windows Phone (previously called Windows Mobile), Sambian OS, and many other
proprietary mobile OSes.
Android is based on Linux with a set of native core C/C++ libraries. Android applications are
written in Java. However, they run on Android's own Java Virtual Machine, called Dalvik Virtual
Machine (DVM), which is optimized to operate on the mobile devices.

2. How to Install Android SDK


Before installing Android SDK, you need to install:
1. Java Development Kit (JDK): .
2. Eclipse:
Step 1: Download the Android SDK
Download the Android SDK from http://developer.android.com/sdk/index.html. For novices,
choose the installer version by clicking the button "Download the SDK for Windows"
(installer_r20-windows.exe).
37

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Step 2: Install Android SDK


Run the downloaded installer into a directory of your choice, e.g., "d:\bin\android-sdk"; or unizp
the downloaded ZIP file. Take note of the installed directory. Hereafter, I shall denote the android
installed directory as <ANDROID_SDK_HOME>.
Step 3: Install Android Platforms and Add-ons via "SDK Manager"
The Android SDK comprises 2 parts: the "tools" and the "Platforms & Add-ons". After running
the installer (in the pervious step), the basic "tools" are installed, which are executables that
support app development. The "Platforms & Add-ons" consist of ALL Android platforms (from
Android 1.x to 4.x) and various Google Add-ons (such as Google Map API), which could be
selectively installed.
Now, we have to choose our Android "Platforms & Add-ons".
1. Launch Android's "SDK Manager", which is responsible for managing the software
components. If you have run the installer, it should have started the SDK Manager after
the installation. Otherwise, launch the SDK manager by running (double-clicking) "SDK
Manager.exe" under the Android installed directory.
2. In "Add Platforms and Packages", select your target Android platforms and add-ons
packages. For novices, select "Android SDK Platform-Tools", and at least one Android
platform (e.g., Android 4.1 (API 16)) "Install".
Step 4: Install Eclipse Android Development Tool (ADT) Plugin
I suppose that you have installed Eclipse.
1. Launch Eclipse.
2. Install Eclipse ADT: From Eclipse's "Help" menu "Install New Software..." In
"Work with", enter https://dl-ssl.google.com/android/eclipse/ Check ALL boxes
Next Finish Restart Eclipse to use ADT plugin.
3. Configure Eclipse ADT: From Eclipse's "Window" menu Preferences Android In
"SDK Location", select the Android SDK installed directory (e.g., "d:\bin\android-sdk").
Step 5: Create a Android Virtual Device (AVD) (or Emulator) via "AVD Manager"
AVDs are emulators that allow you to test your application without the real devices. You can
create AVDs for different android platforms (from Android 1.x to Android 4.x) and
configurations (e.g., screen size, orientation, SD card and its capacity).
1. From Eclipse's "Window" menu Preferences Android In "SDK Location", enter
your Android SDK installed directory (e.g., "d:\bin\android-sdk").
2. From "Window" menu AVD Manager. (You could also start the AVD manager by
running "AVD Manager.exe" under the Android SDK installed directory.)
3. In "Android Virtual Device Manager" dialog "New".
4. The "Create New Android Virtual Device (AVD)" dialog appears. In "Name", enter
"Android41_Phone". Select the "Target" Android platform, "SD Card Size" (e.g., 10MB,
do not set a huge SD Card size, which would take hours to create.) Skin (screen
resolution, e.g., WVGA800x480 for smart phone - Wiki "Graphics display resolution" for
the various resolution) "Create AVD".
You can test your AVD by launching the emulator. Start the AVD manager Select a AVD
Click the "Start" button Check "Scale display to real size" to get a smaller screen that could fit
in your display Launch. Wait patiently! The emulator is very slow and take a few MINUTES
38

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

to launch. You can change the orientation (between portrait and landscape) of the the emulator
via "Ctrl-F11"
Exercise 9:
Write an android application program that displays hello world using terminal.
Launch Eclipse
1. From "File" menu New Project.. Android Application Project Next.
2. The "New Android Project" dialog appears:
1. In "Application Name", enter "Hello Android" (this is the Android appliation
name that shows up on the real device).
2. In "Project Name", enter "HelloAndroid" (this is the Eclipse's project name).
3. In "Package Name", enter "com.example.helloandroid".
4. In "Build SDK", select the latest version (e.g., Android 4.1 (API 16)).
5. In "Minimum Required SDK", select "API 8 Android 2.2 (Froyo)" - almost all of
the Android devices meet this minimum requirement Next.
3. The "Configure Launcher Icon" dialog appears, which allows you to set the application's
icon to be displayed on the devices Next.
4. The "Create Activitiy" dialog appears. Check "Create Activity" Box Select
"BlankActivity" Next.
5. The "New Blank Activity" dialog appears.
1. In "Activity Name", enter "HelloActivity".
2. In "Layout Name", enter "activity_hello" (default).
3. In "Title", enter "Hello" (this title will appear as the screen title) Finish.
Eclipse ADT creates a default Hello-world Android app.
Run the application by right-click on the project node "Run As" "Android Application".
Once the emulator started, unlock the device by holding and sweeping the "lock" to the right (or
left). It shall launch your Hello-world app, and displays "Hello, world!" on the screen with a title
"Hello".
If your program is not launched automatically, try launching it from the "app menu" manually,
after the emulator is started. Look for the icon "Hello".

39

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Trying launching the app from "HOME" "..." Look for the icon "Hello".
Also try "HOME" "..." "MENU" "Manage Apps" Select "HelloAndroid" Uninstall.

40

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Source code:
Expand the "src" node. Expand the "com.example.helloandroid" package node.
Open the "HelloActivity.java", and replace it with the following codes:
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
// Construct a TextView UI component
textView.setText("Hello,world");
// Set the text message for TextView
setContentView(textView);
// this Activity sets its content to the TextView
}
}

41

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Exercise 10:
Write an android application program that displays hello world using eclipse
Launch Eclipse
1. From "File" menu New Project.. Android Application Project Next.
2. The "New Android Project" dialog appears:
1. In "Application Name", enter "Hello Android" (this is the Android appliation
name that shows up on the real device).
2. In "Project Name", enter "HelloAndroid" (this is the Eclipse's project name).
3. In "Package Name", enter "com.example.helloandroid".
4. In "Build SDK", select the latest version (e.g., Android 4.1 (API 16)).
5. In "Minimum Required SDK", select "API 8 Android 2.2 (Froyo)" - almost all of
the Android devices meet this minimum requirement Next.
3. The "Configure Launcher Icon" dialog appears, which allows you to set the application's
icon to be displayed on the devices Next.
4. The "Create Activitiy" dialog appears. Check "Create Activity" Box Select
"BlankActivity" Next.
5. The "New Blank Activity" dialog appears.
1. In "Activity Name", enter "HelloActivity".
2. In "Layout Name", enter "activity_hello" (default).
3. In "Title", enter "Hello" (this title will appear as the screen title) Finish.
Eclipse ADT creates a default Hello-world Android app.
Run the application by right-click on the project node "Run As" "Android Application".
Once the emulator started, unlock the device by holding and sweeping the "lock" to the right (or
left). It shall launch your Hello-world app, and displays "Hello, world!" on the screen with a title
"Hello".
If your program is not launched automatically, try launching it from the "app menu" manually,
after the emulator is started. Look for the icon "Hello".

42

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Trying launching the app from "HOME" "..." Look for the icon "Hello".
Also try "HOME" "..." "MENU" "Manage Apps" Select "HelloAndroid" Uninstall.

43

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Source code:
Expand the "src" node. Expand the "com.example.helloandroid" package node.
Open the "HelloActivity.java", and replace it with the following codes:
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
// Construct a TextView UI component
textView.setText("Hello,world");
// Set the text message for TextView
setContentView(textView);
// this Activity sets its content to the TextView
}
}

44

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Exercise 11:
Write an android application program that accepts input from the user and displays the
hello name to the user in response as output using eclipse
package com.javapapers.android.form;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class FrmActivity extends Activity
{
Button mButton;
EditText mEdit;
TextView mText;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frm);
mButton = (Button)findViewById(R.id.button1);
mButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view) {
mEdit = (EditText)findViewById(R.id.editText1);
mText = (TextView)findViewById(R.id.textView1);
mText.setText("Welcome "+mEdit.getText().toString()+"!");
}
}
}
}

45

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Output:

Exercise 12:
Write an android
demonstrates

application program that


different layouts in android.

Android supports

the following ViewGroups:


LinearLayout
AbsoluteLayout
TableLayout
RelativeLayout
FrameLayout

46

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Figure 1 Creating a new Android project using Eclipse


.
LinearLayout
The LinearLayout arranges views in a single column or single row. Child views can either be
arranged vertically or horizontally.
<?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"
/>
47

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

</LinearLayout>
In the main.xml file, observe that the root element is <LinearLayout> and it has a <TextView>
element contained within it. The <LinearLayout> element controls the order in which the views
contained within it appear.
Each View and ViewGroup has a set of common attributes, some of which are shown in Table 1.
Attribute
layout_width
layout_height
layout_marginTop
layout_marginBottom
layout_marginLeft
layout_marginRight
layout_gravity
layout_weight

Description
Specifies the width of the View or ViewGroup
Specifies the height of the View or ViewGroup
Specifies extra space on the top side of the View or ViewGroup
Specifies extra space on the bottom side of the View or ViewGroup
Specifies extra space on the left side of the View or ViewGroup
Specifies extra space on the right side of the View or ViewGroup
Specifies how child Views are positioned
Specifies how much of the extra space in the layout to be allocated to the

View
layout_x
Specifies the x-coordinate of the View or ViewGroup
layout_y
Specifies the y-coordinate of the View or ViewGroup
Table 1 Common attributes of views and viewgroups
Note that some of these attributes are only applicable when a View is in certain specific
ViewGroup(s). For example, the layout_weight and layout_gravity attributes are only applicable
if a View is either in a LinearLayout or TableLayout.
For example, the <TextView> element above has its width filling up the entire width of its parent
(which is the screen in this case) using the fill_parent constant. Its height is indicated by the
wrap_content constant, which means that its height is the height of its content (in this case, the
text contained within it). If you do not wish to have the <TextView> view occupy the entire row,
you can set its layout_width attribute to wrap_content, like this:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
This will set the width of the view to be equal to the width of the text contained within it. You
can also set the width to an absolute value, like this:
48

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

<TextView
android:layout_width="105px"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
In this case, the width is set to 105 pixels wide. modify the main.xml file by adding a <Button>
view as shown below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:layout_width="105px"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:layout_width="100px"
android:layout_height="wrap_content"
android:text="Button"
/>
</LinearLayout>
Figure 3 shows the views laid out from left to right.

49

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Figure 3 The views laid out in LinearLayout


The default orientation of LinearLayout is set to horizontal. If you want to change its orientation
to vertical, set the orientation attribute to vertical, like this:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>

Figure 4 shows the effect of changing the orientation to vertical.

50

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Figure 4 Changing the orientation to vertical


InLinearLayout, you can apply the layout_weight and layout_gravity attributes to views
contained within it, as the following modifications to main.xml shows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
>
<TextView
android:layout_width="105px"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:layout_width="100px"
android:layout_height="wrap_content"
android:text="Button"
android:layout_gravity="right"
android:layout_weight="0.2"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_weight="0.8"
51

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

/>
</LinearLayout>
Figure 5 shows that the button is aligned to the right of its parent (which is the LinearLayout)
using the layout_gravity attribute. At the same time, you use the layout_weight attribute to
specify the ratio in which the Button and EditText views occupy the remaining space on the
screen. The total value for the layout_weight attribute must be equal to 1.

Figure 5 Applying the layout_weight and layout_gravity attributes


AbsoluteLayout
The AbsoluteLayout lets you specify the exact location of its children. Consider the following UI
defined in main.xml:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<Button
android:layout_width="188px"
android:layout_height="wrap_content"
android:text="Button"
android:layout_x="126px"
android:layout_y="361px"
/>
<Button
android:layout_width="113px"
android:layout_height="wrap_content"
android:text="Button"
android:layout_x="12px"
52

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

android:layout_y="361px"
/>
</AbsoluteLayout>
Figure 6 shows the two Button views located at their specified positions using the
android_layout_x and android_layout_y attributes.

Figure 6 Views laid out using AbsoluteLayout


Author's Note. You should ideally use AbsoluteLayout when you need to reposition your views
when there is a change in the screen rotation.
TableLayout
The TableLayout groups views into rows and columns. You use the <TableRow> element to
designate a row in the table. Each row can contain one or more views. Each view you place
within a row forms a cell. The width for each column is determined by the largest width of each
cell in that column.

Populate main.xml with the following elements and observe the UI as shown in Figure 7.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#000044">
<TableRow>
<TextView
android:text="User Name:"
android:width ="120px"
53

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

/>
<EditText
android:id="@+id/txtUserName"
android:width="200px" />
</TableRow>
<TableRow>
<TextView
android:text="Password:"
/>
<EditText
android:id="@+id/txtPassword"
android:password="true"
/>
</TableRow>
<TableRow>
<TextView />
<CheckBox android:id="@+id/chkRememberPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Remember Password"
/>
</TableRow>
<TableRow>
<Button
android:id="@+id/buttonSignIn"
android:text="Log In" />
</TableRow>
</TableLayout>

54

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Figure 7 Using the TableLayout

Note that in the above example, there are two columns and four rows in the TableLayout. The
cell directly under the Password TextView is populated with an empty element. If you don't do
this, the Remember Password checkbox will then appear under the Password TextView, like that
shown in Figure 8.

Figure 8 Note the change in the position of the Remember Password view
RelativeLayout
The RelativeLayout lets you specify how child views are positioned relative to each other.
Consider the following main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/RLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:id="@+id/lblComments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Comments"
android:layout_alignParentTop="true"
55

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

android:layout_alignParentLeft="true"
/>
<EditText
android:id="@+id/txtComments"
android:layout_width="fill_parent"
android:layout_height="170px"
android:textSize="18sp"
android:layout_alignLeft="@+id/lblComments"
android:layout_below="@+id/lblComments"
android:layout_centerHorizontal="true"
/>
<Button
android:id="@+id/btnSave"
android:layout_width="125px"
android:layout_height="wrap_content"
android:text="Save"
android:layout_below="@+id/txtComments"
android:layout_alignRight="@+id/txtComments"
/>
<Button
android:id="@+id/btnCancel"
android:layout_width="124px"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_below="@+id/txtComments"
android:layout_alignLeft="@+id/txtComments"
/>
</RelativeLayout>
Notice that each view embedded within the RelativeLayout have attributes that allow them to
align with another view. These attributes are:
layout_alignParentTop
layout_alignParentLeft
layout_alignLeft
layout_alignRight
layout_below
layout_centerHorizontal
The value for each of these attributes is the ID for the view that you are referencing. The above
XML UI creates the screen shown in Figure 9.

56

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Figure 9 Using RelativeLayout to layout views


FrameLayout
The FrameLayout is a placeholder on screen that you can use to display a single view. Views that
you add to a FrameLayout is always anchored to the top left of the layout. Consider the
following content in main.xml:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="@+id/widget68"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="40px"
android:layout_y="35px"
>
<ImageView
android:src = "@drawable/androidlogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</FrameLayout>
</AbsoluteLayout>
Here, you have a FrameLayout within an AbsoluteLayout. Within the FrameLayout, you embed
an ImageView view. The UI is as shown in Figure 10.
Note: This example assumes that the res/drawable folder has an image named androidlogo.png.

57

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Figure 10 Using FrameLayout


If you add another view (such as a Button view) within the FrameLayout, the view will overlap
the previous view (see also Figure 11):
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="@+id/widget68"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="40px"
android:layout_y="35px"
>
<ImageView
android:src = "@drawable/androidlogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:layout_width="124px"
android:layout_height="wrap_content"
android:text="Print Picture"
/>
</FrameLayout>
</AbsoluteLayout>
58

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Figure 11 Overlapping views


You can add multiple views to a FrameLayout, but each will stack on top of the previous one.
Exercise 13:
Write an android application program that converts the temperature from Celsius to
Fahrenheit.
package com.example.converttemperatureexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class ConvertTempertureExample extends Activity
{
private EditText text;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(R.id.editText1);
}
// This method is called at button click because we assigned the name to the
// "On Click property" of the button
public void myClickHandler(View view)
{
59

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

switch (view.getId())
{
case R.id.button1:
RadioButton celsiusButton = (RadioButton) findViewById(R.id.radio0);
RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radio1);
if (text.getText().length() == 0)
{
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_LONG).show();
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
if (celsiusButton.isChecked())
{
text.setText(String
.valueOf(convertFahrenheitToCelsius(inputValue)));
celsiusButton.setChecked(false);
fahrenheitButton.setChecked(true);
} else
{
text.setText(String
.valueOf(convertCelsiusToFahrenheit(inputValue)));
fahrenheitButton.setChecked(false);
celsiusButton.setChecked(true);
}
break;
}
}
// Converts to celsius
private float convertFahrenheitToCelsius(float fahrenheit)
{
return ((fahrenheit - 32) * 5 / 9);
}
// Converts to fahrenheit
private float convertCelsiusToFahrenheit(float celsius)
{
return ((celsius * 9) / 5) + 32;
}
}
Compile and build the project.
Output:
60

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

61

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Exercise 14:
Write an android application that shows how to use intents in mobile application
development
Intents are a powerful concept as they allow the creation of loosely coupled applications. Intents
can be used to communicate between any installed application components on the device.
Create a project IntentBrowser
Put the following code in layout/main.xml:
<?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"
android:layout_gravity="center"
>
<Button android:id="@+id/Button01" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Browser"
android:onClick="openBrowser"></Button>
</LinearLayout>
We will start a new Intent with the method :
62

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

Intent i = new Intent("android.intent.action.VIEW",


Uri.parse("http://www.google.com"));
As your activity gets called with intent you can get the data from the intent and display it in your
application.
In this example click event of the button will open Browser.
Run the application.
Steps to Create:
Open Eclipse. Use the New Project Wizard and select Android Project Give the respective
project name i.e. IntentBrowser. Enter following information:
Project name: IntentBrowser
Build Target: Android 2.3
Application name: IntentBrowser
Package name: com.sample.IntentBrowser
Create Activity: IntentBrowser

On Clicking Finish IntentBrowser code structure is generated with the necessary Android
Packages being imported along with IntentBrowser.java. IntentBrowser class will look like
following:
Source Code:
package com.sample.IntentBrowser;
import android.app.Activity;
import android.content.Intent;
63

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

Mobile Application Development


Manual

Laboratory

import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class IntentBrowser extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void openBrowser(View view)
{
Intent i = new Intent("android.intent.action.VIEW",
Uri.parse("http://www.google.com"));
startActivity(i);
}
}
Output:

64

AVANTHI INSTUTE OF ENGINEERING AND TECHNOLOGY


Department of Computer Science and Engineering

You might also like